FileStream: used by another process error

A9S6 picture A9S6 · Mar 5, 2010 · Viewed 21.4k times · Source

I have two different modules that need access to a single file (One will have ReadWrite Access - Other only Read). The file is opened using the following code in one of the modules:

FileStream fs1 = new FileStream(@"D:\post.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.Read);

Th problem is that the second module fails while trying to open the same file using the following code:

FileStream fs = new FileStream(@"D:\post.xml", FileMode.Open, FileAccess.Read);

Do I need to set some additional security parameters here?

Answer

curtisk picture curtisk · Mar 5, 2010

On the FileStream that only READS the file, you need to set it as

FileShare.ReadWrite

FileStream fs = new FileStream(@"D:\post.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

other wise the original FileStream would not be able to write back to it...its just a volley back and forth between the two streams, make sure you hand back what the other needs