小编典典

使用File.Create()后,另一个进程正在使用该文件

c#

我正在尝试检测文件是否在运行时存在,如果不存在,请创建它。但是,当我尝试写入该错误时,我得到此错误:

该进程无法访问文件“ myfile.ext”,因为它正在被另一个进程使用。

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 
}

关于如何解决它的任何想法?


阅读 346

收藏
2020-05-19

共1个答案

小编典典

File.Create方法创建文件并在文件上打开一个FileStream。因此,您的文件已经打开。您根本不需要file.Create方法:

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

StreamWriter如果文件存在,则构造函数中的布尔值将导致附加内容。

2020-05-19