In C#, if 2 processes are reading and writing to the same file, what is the best way to avoid process locking exceptions?

Iain picture Iain · Oct 21, 2008 · Viewed 41.5k times · Source

With the following file reading code:

using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
    using (TextReader tr = new StreamReader(fileStream))
    {
        string fileContents = tr.ReadToEnd();
    }
}

And the following file write code:

using (TextWriter tw = new StreamWriter(fileName))
{
    tw.Write(fileContents);
    tw.Close();
}

The following exception details are seen:

The process cannot access the file 'c:\temp\myfile.txt' because it is being used by another process.

What is the best way of avoiding this? Does the reader need to retry upon receipt of the exception or is there some better way?

Note that the reader process is using a FileSystemWatcher to know when the file has changed.

Also note that, in this instance, I'm not looking for alternatives ways of sharing strings between the 2 processes.

Answer

Jeff Yates picture Jeff Yates · Oct 21, 2008

You can open a file for writing and only lock write access, thereby allowing others to still read the file.

For example,

using (FileStream stream = new FileStream(@"C:\Myfile.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
   // Do your writing here.
}

Other file access just opens the file for reading and not writing, and allows readwrite sharing.

using (FileStream stream = new FileStream(@"C:\Myfile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
   // Does reading  here.
}

If you want to ensure that readers will always read an up-to-date file, you will either need to use a locking file that indicates someone is writing to the file (though you may get a race condition if not carefully implemented) or make sure you block write-sharing when opening to read and handle the exception so you can try again until you get exclusive access.