“ System.IO.IOException:该进程无法访问文件'C:\ Test \ test.txt',因为它正在被另一个进程使用”

时间:2019-02-26 22:06:41

标签: c# .net

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"

这次我在做什么错了?

1 个答案:

答案 0 :(得分:6)

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");
        }
    }
}