FileStream: used by another process error
Solution 1
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
Solution 2
When opening the second FileStream
, you also need to specify FileShare.Read
, otherwise it will try to open it with exclusive access, and will fail because the file is already open
A9S6
Software Developer Enjoys Motorcycling, Cooking, Traveling, Photography, Movies, UFO talks and Debugging life.
Updated on July 09, 2022Comments
-
A9S6 almost 2 years
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?
-
A9S6 about 14 yearsTried that but it did not work: FileStream fs = new FileStream(@"D:\post.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
-
A9S6 about 14 years+1: OK it worked but I dont know why. Will the first FileStream be able to save while the second one is open?
-
behrus about 14 yearsWith a quick test, I was able to write to the first then close the stream all while the other was open and has the CanRead status return true....so looks that way, yes
-
Partha about 4 yearsNote that even if you open FileAccess.Read , you need to specify the FileShare.ReadWrite , if another one opened this with FileShare.ReadWrite already. All the FileStreams must have the same FileShare Mode.