在编写一些处理日志和文件的代码时,我在 Windows 文件 io 中发现了一些令人困惑的行为。有谁知道为什么这个测试会失败并显示“无法读取文件”消息?
[TestMethod]
public void SouldAllowReads()
{
using (var file = File.Open(_path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
using (var file2 = File.Open(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
//works ok, doesn't throw
}
try
{
using (var file3 = File.Open(_path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
//fails
}
}
catch (IOException)
{
Assert.Fail("cannot read file");
}
}
}
附言。 _path = Path.GetTempFileName();
编辑:
我会将第一个答案标记为正确答案,但在这个设计中有一件事困扰着我。 .NET 方法(例如 File.ReadAllText(_path))会抛出异常,这是不应该发生的。
例如,这个剪断了我的测试也会失败断言:
try
{
string text = File.ReadAllText(_path);
}
catch (IOException)
{
Assert.Fail("cannot read file");
}
最佳答案
您有 var file = open with FileAccess.Write,同时尝试使用不允许并发写访问的文件共享模式 FileShare.Read 打开 var file3 =。
关于c# - 为什么 FileShare 不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7132348/