Jes*_*ard 2 c# file streamwriter race-condition
我有一种情况,需要检查txt文件是否存在,如果不存在,则需要创建它。
在此之后,我需要立即用一些文本填充文件。
这是我的代码如下所示:
if (!File.Exists(_filePath))
{
File.Create(_filePath);
}
using (var streamWriter = File.AppendText(_filePath))
{
//Write to file
}
Run Code Online (Sandbox Code Playgroud)
System.IO.IOException仅在必须创建新文件时,我在第5行收到异常()。这是例外:
The process cannot access the file '**redacted file path**' because it is being used by another process.
我不想添加Thread.Sleep(1000);,因为这是一个糟糕的解决方案。
有没有办法找出何时该文件再次可用,以便我可以对其进行写入?
小智 5
只需将StreamWriter与param结合使用append = true。如果需要,它将创建文件。
using (StreamWriter sw = new StreamWriter(_filePath, true, Encoding.Default))
{
sw.WriteLine("blablabla");
}
Run Code Online (Sandbox Code Playgroud)
小智 5
FileCreate方法返回Filestream,在使用StreamWriter之前应关闭该文件流
if (!File.Exists(_filePath))
{
// close fileStream
File.Create(_filePath).Close();
}
using (var streamWriter = File.AppendText(_filePath))
{
//Write to file
}
Run Code Online (Sandbox Code Playgroud)