简体   繁体   English

为什么FileShare无法按预期工作?

[英]Why doesn't FileShare work as expected?

While writing some code dealing with logs and files, I've discovered some baffling behaviour in windows file io. 在编写一些处理日志和文件的代码时,我发现Windows文件io中有些令人困惑的行为。 Does anyone know why this test would fail with "cannot read file" message? 有谁知道为什么该测试会失败并显示“无法读取文件”消息?

[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");
        }
    }
}

PS. PS。 _path = Path.GetTempFileName(); _path = Path.GetTempFileName();

EDIT: 编辑:

I'll mark elevener answer as correct one, but there is one thing that bothers me in this design. 我会将第11个答案标记为正确的答案,但是在此设计中有一件事困扰着我。 .NET methods such as File.ReadAllText(_path) throw exceptions, which just shouldn't happen. .NET方法(例如File.ReadAllText(_path))会引发异常,这是不应该发生的。

For example this snipped my test would also fail assertion: 例如,这扼杀了我的测试也将使断言失败:

        try
        {
            string text = File.ReadAllText(_path);
        }
        catch (IOException)
        {
            Assert.Fail("cannot read file");
        }

您有var file =用FileAccess.Write打开,并且同时试图以文件共享模式FileShare.Read打开var file3 =,不允许同时进行写访问。

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

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