Harsh Jani

Harsh Jani

  • NA
  • 34
  • 53.7k

How do I solve the given error

May 16 2015 5:37 AM
Hi,

I am trying to create a log file using the code given below, but it throws "Process cannot access a file because it is being used by another process" error. The code is as follows: -

private static void CreateLogFile(int TaskId = 0, string TaskName = "", string ServiceName = "", Exception EX = null)
{
string logFile = System.IO.Directory.GetCurrentDirectory() + "\\LogFile\\" + DateTime.Now.ToString("dd-MM-yyyy") + "TaskLogFile.txt";
string logMessage = string.Empty;
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);

}

}

Also, I am calling this method with other async methods. Kindly help me out in this regard.

Thanks

Answers (1)