tags:

views:

147

answers:

2

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"

+3  A: 

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.

mafutrct
+1  A: 

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.

Burkhard
Where exactly? For the reading or the writing stream?
mafutrct
I think that would not help much, since this would require even more rights on the file than the code in the OP did. Did you possibly mean *FileShare*? That's what worked for me, as seen in my answer.
mafutrct
In C/C++ I can open a file either in read, write or readwrite mode. In the last mode, I can read and write to the file. I'm sorry, I don't know much about C# and the required rights.
Burkhard
Ah, I think you misunderstood the question. You are right, FileAccess specifies whether we want to read/write/both. The important part, however, was the sharing mode. It turned out that the file has to be opened for reading with read-write-sharing after opening it for writing earlier.
mafutrct