Search code examples
c#.netfile-iofilestream

FileStream: used by another process error


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?


Solution

  • 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);
    

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