I have the C# console application
which writes the step it is doing in a Log text file using the code below
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("dd-MM-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath,FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine("---------------" + DateTime.Now.ToString() + "--------------------------");
log.WriteLine(strLog);
log.WriteLine("---------------------------------------------------------------");
log.Close();
It works fine but when an exception occurs I will attach the log text file to the mail and send it after that when I try to invoke the Method again which writes into the same log text file after mail with log text file attachment I get the exception IOException: The process cannot access the file 'file path' because it is being used by another process
I had tried FileShare Option and other things nothing worked out
Exception is thrown in the below code
client.Send(mail);
client.Dispose();
LogWriter.WriteLog("######--Re-Start of the Process at -" + Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss")) + "--######"); //Exception thrown here
Console.WriteLine("######--Re-Start of the Process at -" + Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss")) + "--######");
BridgePage.GetData();
Console.WriteLine("######--Re-End of the Process at -" + Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss")) + "--######");
LogWriter.WriteLog("######--Re-End of the Process at -" + Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss")) + "--######");
As per the comment to use FileInfo.AppendText by Panagiotis Kanavos tried the below code, but still same exception
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("dd-MM-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
if (!logFileInfo.Exists)
{
//Create a file to write to.
using (StreamWriter logsw = logFileInfo.CreateText())
{
logsw.WriteLine("---------------" + DateTime.Now.ToString() + "--------------------------");
logsw.WriteLine(strLog);
logsw.WriteLine("---------------------------------------------------------------");
}
}
else
{
using (StreamWriter logsw = logFileInfo.AppendText())
{
logsw.WriteLine("---------------" + DateTime.Now.ToString() + "--------------------------");
logsw.WriteLine(strLog);
logsw.WriteLine("---------------------------------------------------------------");
}
}
Please help