views:

228

answers:

3

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?

A: 

you need to use the filestreamname.Open(); and the filestreamname.close(); command when using 2 filestreams that read/write to the same file, because you can't read and write to a file asynchronously.

Timmo
-1: Completely incorrect information.
Moron
A: 

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

Thomas Levesque
Tried that but it did not work: FileStream fs = new FileStream(@"D:\post.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
A9S6
+2  A: 

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

curtisk
+1: OK it worked but I dont know why. Will the first FileStream be able to save while the second one is open?
A9S6
With 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
curtisk