Search code examples
c#fileiostreamwriter

System.IO.IOException: The process cannot access the file '.txt' because it is being used by another process


I am using the next code to log errors of an web application.

using (StreamWriter myStream = new StreamWriter(sLogFilePath, true))
{                
myStream.WriteLine(string.Format("{0, -45}{1, -25}{2, -10 {3}", guid, DateTime.Now, StringEnum.GetStringValue(enumMsg), sText));      

}

Sometimes, the following exception 'System.IO.IOException: The process cannot access the file '.txt' because it is being used by another process.' is thrown.

I think this is caused by multiple instances of the web app at the same time. Can you help me fix this problem, please ?

EDIT: I have to add that for every method I log like this:

Date - Method X started.

Date - Exception.Message (table not found or other errors)

Date - Method X stopped.

and when this Error appears, it's logged only this:

Date - System.IO.IOException: The process cannot access the file '.txt' because it is being used by another process.


Solution

  • I've added this code to my class:

     public static bool IsFileLocked(FileInfo file)
            {
                FileStream stream = null;
    
                try
                {
                    stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                }
                catch
                {
                    return true;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }
    
                return false;
            }
    

    and now my LogToFile method is like this:

    while (IsFileLocked(fi))
                {
                }
    
                using (StreamWriter myStream = new StreamWriter(sLogFilePath, true))
                {
                    if (displayTime == true)
                        myStream.WriteLine(string.Format("{0, -45}{1, -25}{2, -10}{3}", guid, DateTime.Now, StringEnum.GetStringValue(enumMsg), sText));
                    else
                        myStream.WriteLine(string.Format("{0, -70}{1, -10}{2} ", guid, StringEnum.GetStringValue(enumMsg), sText));                
                }
    

    I hope this will work.