当我创建我log.txt
的 withFile.Create(Path.Combine(PATH, NAME));
然后尝试从中读取时,我得到一个异常:{System.IO.IOException: The process cannot access the file 'c:\temp\log.txt' because it is being used by another process.
.
如果log.txt
文件退出并且没有在该方法中创建,我可以读取和写入日志而不会出现任何问题。
创建的是log.txt
异步的,问题是程序在创建之前试图读取它吗?
public static void WriteToLog(string text)
{
try
{
if (!Directory.Exists(PATH))
{
Directory.CreateDirectory(PATH);
}
if( !File.Exists(Path.Combine(PATH, NAME)) )
{
File.Create(Path.Combine(PATH, NAME));
}
var logLines = File.ReadAllLines(Path.Combine(PATH, NAME)).ToList<string>();
logLines.Insert(0, "-------------------------------------------------End New Log");
logLines.Insert(0, text);
logLines.Insert(0, "-------------------------------------------------Start New Log");
File.WriteAllLines(Path.Combine(PATH, NAME), logLines);
}
catch (Exception ex)
{
}
}