Log File

M

MFRASER

I am trying to create a simple log file function that logs the timespan and
a message. Problem with my code is that I get an error that the file is
being access by another process. What am I doing wrong?

try

{


System.IO.StreamWriter MainWriter =
File.AppendText(c:\\ImportXMLTimeLog.txt");

System.TimeSpan TimeDiff = System.DateTime.Now.Subtract(aStartTime);

MainWriter.Write(logMessage + ", Minutes: " + TimeDiff.Minutes + ", Seconds:
" + TimeDiff.TotalSeconds + " , MiliSeconds: " + TimeDiff.TotalMilliseconds
+ "\r\n");

MainWriter.WriteLine("");

// Update the underlying file.

MainWriter.Flush();

MainWriter.Close();

}

catch{}
 
K

Kirk Graves

MFRASER,

I would recommend closing the MainWriter object in the finally block. If
something goes wrong, the file could be opened, then not closed properly
before the next attempt to log something.

Can you change the process so you don't have to open and close the
MainWriter every time you want to log something? This could have 2
benefits. First is performance. If you log things very often you are doing
a lot of work opening and closing that file. Second, the chance for locking
that file is reduced since you have less chance of leaving it open before
trying to re-open it.

Finally, you might just have to plan for the potential of having that file
locked up. What if 2 copies of your application are running at the same
time? They could be contending for the right to access the file and one of
them consitently gets blocked. You might open a new file in the catch
statement and write to that file instead.

Just the babblings of a geek.

Kirk Graves
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top