File.Create 和 File.OpenRead 以及 IOException
我需要读取在程序的其他部分打开以进行写入的文件
const string fileName = "file.bin";
FileStream create = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read);
FileStream openRead = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
最后一行引发 IOException:
"The process cannot access the file because it is being used by another process"
请帮助正确配置 File.Open 参数。
I need to read a file that is opened for writing in other part of the program
const string fileName = "file.bin";
FileStream create = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read);
FileStream openRead = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
The last line raises IOException:
"The process cannot access the file because it is being used by another process"
Please help properly configure File.Open parameters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将两个语句中的
FileShare
参数更改为FileShare.ReadWrite
:来自 MSDN 的
ReadWrite
标志描述:Change
FileShare
parameter toFileShare.ReadWrite
in both statement:ReadWrite
flag description from MSDN:要完成 Reniuz 的回答,您可以执行以下操作:
注意第一个 FileStream 用于写入访问的
FileShare.Read
。写入流允许其他流读取它。在写入器流中设置FileShare.ReadWrite
似乎不安全。用于读取访问的第二个流实际上需要设置 FileShare.ReadWrite,因为参数 FileShare 定义了其他流的权限。如果您仅设置
FileShare.Read
而另一个流已打开以供写入,则读取器流根本无法满足FileShare.Read
权限(这隐式表明该流无法写入通过另一个流)。我认为 FileAccess 和 FileShare 这两个参数之间存在天然的混淆。第一个基本上是您创建的流的权限,第二个是任何其他流的权限。
To complete Reniuz's answer, you can do this :
Notice
FileShare.Read
for the first FileStream for write access. The write stream allows other streams to read it. It doesn't seem safe to setFileShare.ReadWrite
in the writer stream.The second stream for read access effectively need to set
FileShare.ReadWrite
because the parameter FileShare defines the permissions for other streams. If you set onlyFileShare.Read
while another stream is already open for write, the reader stream simply cannot fulfill theFileShare.Read
permission (which implicitly says the stream cannot be written by another stream).I think there is a natural confusion between the two parameters FileAccess and FileShare. The first is basically the permission of the stream you create, the second is for any other.
您需要先使用 .Close() 方法关闭文件。
You need to close the file first with the .Close() method.
第一个流将写入文件,而第二个流只允许读取
The first stream is going to write to the file whereas the second one permits reading only
使用 FileShare.ReadWrite 来实现:
Use
FileShare.ReadWrite
for that: