使用File.Create后的文件正在由另一个进程() [英] File being used by another process after using File.Create()

查看:319
本文介绍了使用File.Create后的文件正在由另一个进程()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图来检测文件是否存在在运行时,如果没有,创建它。然而,当我试图写它,我得到这个错误:


  

,因为它正由另一个进程的进程无法访问该文件'myfile.ext。


 字符串文件路径=的String.Format(@{0} \\为M {1} .DAT,ConfigurationManager.AppSettings [目录路径],costCentre);
如果(!File.Exists(文件路径))
{
    File.Create(文件路径);
}使用(StreamWriter的SW = File.AppendText(文件路径))
{
    //写我的文字
}

如何解决它的任何想法?


解决方案

File.Create 方法创建的文件,并打开一个的FileStream 上的文件。所以你的文件已经打开。你并不真的需要file.Create方法都:

 字符串文件路径= @C:\\ somefilename.txt
使用(StreamWriter的SW =新的StreamWriter(文件路径,真实))
{
    //写入文件
}

的StreamWriter 构造布尔会导致如果该文件存在内容被追加。

I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:

The process cannot access the file 'myfile.ext' because it is being used by another process.

string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
if (!File.Exists(filePath)) 
{ 
    File.Create(filePath); 
} 

using (StreamWriter sw = File.AppendText(filePath)) 
{ 
    //write my text 
}

Any ideas on how to fix it?

解决方案

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

这篇关于使用File.Create后的文件正在由另一个进程()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆