简体   繁体   中英

How does one use FileStream to append to a file without an exclusive lock?

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);

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.

我不确定它是否有帮助,但如果你只是单元测试,使用内存流而不是文件会不会更容易?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM