I have a simple routine in a C# Console Application That writes log file entries. Today, an odd message appeared in the log.
The process cannot access the file 'C:Development-IPLLogfilesLogFile20212.txt' because it is being used by another process.
This is bizarre – the message is written in the file it says it cannot access.
The code looks like this:
public static void WriteLog(string message)
{
var requiredPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\..\"));
// use Logfileyyyyww where yyyy is year & ww is week number
DateTime dateTime = DateTime.Now;
int year = dateTime.Year;
int weekno = WeekNo.GetIso8601WeekOfYear(dateTime);
string filePath = requiredPath + "\Logfiles\LogFile" + year.ToString() + weekno.ToString() + ".txt";
using (StreamWriter writer = new StreamWriter(filePath, true))
{
if (message != null)
{
writer.WriteLine("Date : " + DateTime.Now.ToString() + ": " + message);
}
}
}
I would have thought that the Using statement would ensure that this resource is closed & disposed each time it is used.