gpt4 book ai didi

c# - 日志文件似乎被另一个进程锁定

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:44 25 4
gpt4 key购买 nike

我正在尝试使用下面给出的代码创建一个日志文件,但它抛出了

Process cannot access a file because it is being used by another process

代码如下:

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)

关于c# - 日志文件似乎被另一个进程锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30275643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com