日志文件似乎被另一个进程锁定
本文关键字:另一个 进程 锁定 文件 日志 | 更新日期: 2023-09-27 17:49:32
我试图使用下面给出的代码创建一个日志文件,但它抛出
进程不能访问一个文件,因为它正在被另一个进程使用
代码如下:
string logFile = System.IO.Directory.GetCurrentDirectory() + "''LogFile''" + DateTime.Now.ToString("dd-MM-yyyy") + "TaskLogFile.txt";
StreamWriter LogWriter;
try
{
if (!File.Exists(logFile))
{
LogWriter = new StreamWriter(logFile);
Console.WriteLine("Log File Created...");
}
else
{
LogWriter = File.AppendText(logFile);
Console.WriteLine("Log File Appended...");
}
if (EX == null)
{
LogWriter.Write("'r'nLog Entry : ");
LogWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
LogWriter.WriteLine("'nTask Id = {0} , Task Name = {1}, Service Name = {2} ", TaskId, TaskName, ServiceName);
LogWriter.WriteLine("-----------------------------------------------------------------------------------------------------");
LogWriter.Close();
}
else
{
LogWriter.WriteLine("'n Error : {0}, Error Location : {1},Task ID = {2}, Task Name : {3}, Service Name : {4} " + EX.ToString(), EX.StackTrace, TaskId, TaskName, ServiceName);
}
}
catch (Exception ex)
{
LogWriter = File.AppendText(logFile);
LogWriter.WriteLine("'n Error : {0}, Error Location : {1},Task ID = {2}, Task Name : {3}, Service Name : {4} " + ex.ToString(), Environment.StackTrace, TaskId, TaskName, ServiceName);
}
另外,我用其他异步方法调用这个方法。
您的问题是日志文件可能被另一个进程锁定,或者如果它是异步的,则由同一进程锁定
这是日志文件的一个典型问题,可以通过FileShare.ReadWrite
File.Open(logFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)