简体   繁体   English

如何在没有独占锁的情况下使用FileStream附加到文件?

[英]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). 我在C#/ .NET中尝试使用FileStream做法是打开两个流:一个附加到文件,另一个异步读取这些写入(用于单元测试一些网络连接处理代码)。 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: 我无法弄清楚如何让笔者流开在非EXLUSIVE锁定模式的文件,因此代码总是抛出一个异常:

The process cannot access the file 'C:\\test.txt' because it is being used by another process. 该进程无法访问文件'C:\\ test.txt',因为它正由另一个进程使用。

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 看到这个问题: C#文件读/写fileshare似乎不起作用

In short, your freader has to specify FileShare.Write to allow for the fact that there is already a writer on the file. 简而言之,您的freader必须指定FileShare.Write以允许文件中已有写入程序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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