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

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.


If you create a named Mutex you can define the mutex in the writing application, and have the reading application wait until the mutex is released.

So in the notification process that is currently working with the FileSystemWatcher, simply check to see if you need to wait for the mutex, if you do, it will wait, then process.

Here is a VB example of a Mutex like this that I found, it should be easy enough to convert to C#.


Is there any particular reason for opening the file with FileShare.None? That'll prevent the file from being opened by any other process.

FileShare.Write or FileShare.ReadWrite should allow the other process (subject to permissions) to open and write to the file while you are reading it, however you'll have to watch for the file changing underneath you while you read it - simply buffering the contents upon opening may help here.

All of these answers, however, are equally valid - the best solution depends on exactly what you're trying to do with the file: if it's important to read it while guaranteeing it doesn't change, then lock it and handle the subsequent exception in your writing code; if it's important to read and write to it at the same time, then change the FileShare constant.