【问题标题】:Why doesn't FileShare work as expected?为什么 FileShare 不能按预期工作?
【发布时间】:2011-08-20 14:24:05
【问题描述】:

在编写一些处理日志和文件的代码时,我在 windows 文件 io.xml 中发现了一些令人费解的行为。有谁知道为什么这个测试会因“无法读取文件”消息而失败?

[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。 _path = Path.GetTempFileName();

编辑:

我会将 11 者的答案标记为正确的答案,但在这个设计中有一件事让我感到困扰。 .NET 方法,例如 File.ReadAllText(_path) 抛出异常,这是不应该发生的。

例如,这个剪断我的测试也会失败断言:

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

【问题讨论】:

  • 最后一个 sn-p 在什么情况下给你 IOexcpetion?
  • ReadAllText 抛出异常的事实已记录在案。如果操作失败,您希望/期望发生什么?

标签: c# windows file-io


【解决方案1】:

您使用 FileAccess.Write 打开 var file =,同时尝试使用不允许并发写入访问的文件共享模式 FileShare.Read 打开 var file3 =。

【讨论】:

    猜你喜欢
    • 2021-05-30
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多