【问题标题】:Create a text file and write to it in C# [duplicate]创建一个文本文件并用 C# 写入它[重复]
【发布时间】:2015-01-23 16:24:18
【问题描述】:

您好,我尝试在 C# 中创建和编写文本文件,但出现此错误。

另一个进程正在使用该进程 'D:\SampleFolder\Sample.txt' 无法访问该文件。

public void WriteToLog(string ClassName, string Message)
{
    string path = @"D:\SampleFolder\" + ClassName + ".txt";

    if (!File.Exists(path))
    {
        File.Create(path);
        TextWriter tw = new StreamWriter(path,true);
        tw.WriteLine(DateTime.Now.ToString() + " " + "Class:" + " " + ClassName + " " + "Message:" + Message);
        tw.Close();
    }

    else if (File.Exists(path))
    {
        TextWriter tw = new StreamWriter(path, true);
        tw.WriteLine(DateTime.Now.ToString() + " " + "Class:" + " " + ClassName + " " + "Message:" + Message);
        tw.Close();
    }
}

..
..
try
{

}
catch (Exception ex)
{       
    WriteToLog(this.GetType().Name, ex.Message);
}

【问题讨论】:

  • 确保该文件未被其他应用程序打开。听起来就是这样!有些应用程序是贪婪的,一旦打开它们就会锁定它,这样事情就无法改变它。关闭该应用,然后重试!
  • 文件已经打开了吗?
  • 您是否在文本编辑器中打开了文本文件,或者其他任何程序都无法对其进行修改?
  • File.AppendAllText() 会将您所拥有的内容简化为 1 行

标签: c# file-io


【解决方案1】:

您在创建TextWriter 之前发出File.Create

File.Create(path);
TextWriter tw = new StreamWriter(path,true);

File.Create 默认创建一个文件并将其锁定,因此您的TextWriter 无法访问它。

来自documentation

此方法创建的 FileStream 对象的默认 FileShare 值为 None;在关闭原始文件句柄之前,没有其他进程或代码可以访问创建的文件。

File.Create 返回一个流,因此要么使用该流写入文件(而不是将路径传递给TextWriter),要么根本不调用File.Create,让@987654330 @创建文件。

【讨论】:

  • 也使用using 声明。此外,对于日志记录,请使用现有库。
  • @Dialectus 同意using。不一定要使用现有的库进行日志记录。我只是在回答为什么文件被锁定的问题,以便 OP 可以了解问题所在:我不会使用他用来将单行文本写入文件的方法:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 2020-06-13
  • 2013-02-11
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多