创建一个文本文件并在 C# 中写入

Create a text file and write to it in C#

您好,我尝试用 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);
}

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

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

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

来自documentation:

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

File.Create returns 一个流,所以要么使用该流写入文件(而不是将路径传递给 TextWriter),要么不调用 File.Create,然后让 StreamWriter 创建文件。