c# - "System.IO.IOException: The process cannot access the file ' C :\Test\test. 文本 ' because it is being used by another process"

标签 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"

这次我做错了什么?

最佳答案

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/

相关文章:

c# - 脚本抛出 MySqlException 并显示语法错误消息

javascript - 使复选框成为一组单选按钮

c# - 使用 Application_BeginRequest + 重定向进行 HTML 版本控制中的 Javascript、CSS

.net - Entity Framework EDMX 复制到输出目录

c# - 如何使用 .NET P/调用 CryptUIWizExport 函数

.net - JavaScript XML 注释文档

c# - 需要登录才能观看视频 asp.net

c# - 如何将值传递给 Task.Factory 中的匿名方法

.net - .NET 程序集上的 AppLocker DLL 规则

c# - 键集未定义