File being used by another process. Reason, and solution?

Posted by pstar on Stack Overflow See other posts from Stack Overflow or by pstar
Published on 2010-05-18T22:51:26Z Indexed on 2010/05/18 23:00 UTC
Read the original article Hit count: 140

Filed under:

The process cannot access the file 'abc.log' because it is being used by another process.

Hi, I've seen this exception from my application occationaly but I am still trying to fix that, hope I will get some insight from stackoverflow.

In my application I've have defined a WriteToLog function which will write to a log file. Also the mainForm of my application will launch a backgroundWorker do some job which also calls the WriteToLog. Maybe two threads access a file will cause a problem? But in my code I 've already do my best to write flush and close the text file (I think), and here is my code from WriteToLog:

 StreamWriter sw = null;
 string newText = "";
 try
 {
     //populate the content for newText
     sw = File.AppendText(LOG_FILE);
     sw.Write(newText);
     sw.Flush();
     sw.Close();
 }
 catch (IOException ex)
 {
     MessageBox.Show("Failed to write to log!\n\t" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
 finally
 {
     if (sw != null)
     {
         sw.Close();
     }
 }

I think as long as I flush and close the streamWriter, I should be able call the WriteToLog multi-times and in multi-threads isn't it? Or if I am wrong, could I simple make the file open shared, or there are other reason/solutions?

© Stack Overflow or respective owner

Related posts about c#