views:

2663

answers:

2

What I'm trying to do with FileStream in C#/.NET is to open two streams: one appending to a file and the other reading those writes asynchronously (for unit testing some network connection handling code). I can't figure out how to get the writer stream to open the file in non-exlusive locking mode and thus the code always throws an exception:

The process cannot access the file 'C:\test.txt' because it is being used by another process.

Here's a smattering of code which demonstrates the issue:

FileStream fwriter = new FileStream("C:\\test.txt", FileMode.Append,
    FileAccess.Write, FileShare.Read);
FileStream freader = new FileStream("C:\\test.txt", FileMode.Open,
    FileAccess.Read, FileShare.Read);
+3  A: 

See this question: C# file read/write fileshare doesn’t appear to work

In short, your freader has to specify FileShare.Write to allow for the fact that there is already a writer on the file.

Rob Walker
Thanks for the quick response!
Neil C. Obremski
A: 

I am not sure if it helps, but if you are only unit testing, wouldn't it be easier to use a memory stream instead of files?

Grzenio
Yeah, if I could only figure out how to get a MemoryStream to act more like a connection. Of course I'm still having just as much trouble with FileStream so I may ask another question to that effect.
Neil C. Obremski