mafu
mafu

Reputation: 32730

How to open a file for independent read/write?

I'd like to open the same file for both reading and writing. The file pointer should be independent. So a read operation should not move the write position and vice versa.

Currently, I'm using this code:

FileStream fileWrite = File.Open (path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
FileStream fileRead = File.Open (path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
StreamWriter _Writer = new StreamWriter (fileWrite, new ASCIIEncoding ());
StreamReader _Reader = new StreamReader (fileRead, new ASCIIEncoding ());

But that leads to an IOException: "The process cannot access the file because it is being used by another process"

Upvotes: 2

Views: 696

Answers (2)

Burkhard
Burkhard

Reputation: 14738

I don't have a C# at hand, so I cannot test it.

Can't you just use FileAccess.ReadWrite instead of FileAccess.Read?

Edit: The answer is no. You need to use FileShare to do it.

Upvotes: 1

mafu
mafu

Reputation: 32730

I think I just figured it out myself. In the second File.Open, we're trying to deny other applications write access by specifying FileShare.Read. Instead, we need to allow the first stream to write to the file:

FileStream fileRead = File.Open (path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);

That's inherently correct, as the reading stream should not care about other people writing to the file. At least I don't get an exception anymore.

Upvotes: 4

Related Questions