I’m using StreamWriter to write log file.
And this is the writing log method,
public void Write(string fileNamePrefix, string msg){
GenerateFileName(fileNamePrefix);
string logTime = "> "+DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString()+"\r\n";
using (StreamWriter sw = new StreamWriter(fileName, true))
{
sw.WriteLine(logTime + msg);
sw.Flush();
sw.Close();
sw.Dispose();
}
}
While using that method to write log, I got a error message that say ”
The process cannot access the file ‘C:\Users\mark\documents\visual studio 2010\Projects\eee\eee.WebUI\log\Order_20120613’ because it is being used by another process.“
Not all the time the error message occur, when I run many process at the same time and the processes are using that method to write log, then I get that error message.
anybody knows what I am doing wrong? how to avoid this error?
and is that right way for writing log? How do you write process log usually?
Thank you.
I/O failures are expected behavior for I/O related classes. So prepare to handle them.
In you particular case it is most likely caused by file name collisions – make sure names for “log” files are unique between processes and threads in each process.
Unrelated comments:
There is absolutely no need to call
sw.Flush();sw.Close(); sw.Dispose();if you are usingusing(since it is already correctly callssw.Dispose()including exception cases). Even if you would not do that calling both Close and Dispose is of no value as both just call the same code.Inventing (usually called “reinventing the wheel”) log writing and tracing libraries is traditional developers’ past time. Unless you consider it learning exercise or entertainment please use existing libraries like one that is already part of .Net framework (which lets you configure multiple trace listeners and so on) or other ones like Log4Net.