C# 如何使用 FileStream 附加到没有排他锁的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/189239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:20:47  来源:igfitidea点击:

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

c#.netfilestreamfilestream

提问by Neil C. Obremski

What I'm trying to do with FileStreamin 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 writerstream to open the file in non-exlusive locking mode and thus the code always throws an exception:

我试图FileStream在 C#/.NET 中做的是打开两个流:一个附加到文件,另一个异步读取这些写入(用于单元测试一些网络连接处理代码)。我无法弄清楚如何让作家流开在非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);

采纳答案by Rob Walker

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

看到这个问题:C# 文件读/写文件共享似乎不起作用

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 以允许文件上已经有一个 writer 的事实。

回答by Grzenio

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?

我不确定它是否有帮助,但是如果您只是进行单元测试,那么使用内存流而不是文件不是更容易吗?