A9S6
A9S6

Reputation: 6675

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?

Upvotes: 12

Views: 29496

Answers (3)

curtisk
curtisk

Reputation: 20175

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.

Upvotes: 37

Thomas Levesque
Thomas Levesque

Reputation: 292405

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

Upvotes: 1

Timmo
Timmo

Reputation: 19

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.

Upvotes: 0

Related Questions