【发布时间】: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 行