C# 的新手。尝试迭代写入 .txt
文件,我尝试使用它来实现解决方案:
Create a .txt file if doesn't exist, and if it does append a new line
我是这样写的:
var path = @"C:\Test\test.txt";
try
{
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(message);
tw.Close();
}
else if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(message);
tw.Close();
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
无论文件是否存在,都会产生同样的错误:
"System.IO.IOException: The process cannot access the file 'C:\Test\test.txt' because it is being used by another process"
这次我做错了什么?
最佳答案
File.Create(path);
打开文件并使其保持打开状态。当您执行 TextWriter tw = new StreamWriter(path);
时,您正在尝试访问创建文件的进程正在使用的文件(上面的代码行)。
你应该这样做:
if (!File.Exists(path))
{
using (var stream = File.Create(path))
{
using (TextWriter tw = new StreamWriter(stream))
{
tw.WriteLine("abc");
}
}
}
关于c# - "System.IO.IOException: The process cannot access the file ' C :\Test\test. 文本 ' because it is being used by another process",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54894922/