【问题标题】:IOException - file being used by another process with FileShare.ReadWriteIOException - 另一个进程正在使用 FileShare.ReadWrite 使用的文件
【发布时间】:2021-02-27 13:17:39
【问题描述】:

我一直在为我的问题寻找解决方案,尝试了很多可能性,但是当文件内容被另一个进程使用时,我仍然无法读取文件内容。我希望有人可以提供帮助:)

        using (FileStream fs = File.OpenWrite(file)) //Here I try to simulate that the file is opened for read.
        {
            Assert.NotNull(xmlUtility.Load(file));
        }

这是我想打开它以进行读取访问的代码:

        using (StreamReader fs = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
        {
            doc = XDocument.Load(fs);
        }

【问题讨论】:

  • 为什么要使用OpenWrite 来模拟读取?因为 OpenWrite 拒绝来自其他进程的所有访问:check the remarks section in the documentation
  • 嗯所以基本上这个 File.OpenWrite(file) 使用 FileAccess.None 打开文件,这意味着我无法从任何其他应用程序/代码中打开它吗?
  • 完全正确。可能有办法解决它,但您需要第二个应用程序以更多权限运行,并且可能使用另一个 API 来打开文件。

标签: c# ioexception


【解决方案1】:

看起来根本原因是我模拟了正在打开的文件。该调用“File.OpenWrite()”使用 FileAccess.None 打开文件,从而禁用对文件的其他访问。

感谢 Sidewinder94:)

如果我使用其他方法来模拟文件打开,那么给定的示例也可以。

【讨论】:

    【解决方案2】:

    你能用记事本...word打开它吗?

    using (var fs = new FileStream(path, FileMode.Open, 
    FileAccess.Read, FileShare.ReadWrite))
    using (var sr = new StreamReader(fs, Encoding.Default)) {
    // read the stream
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 2011-09-04
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 2013-12-01
      • 2021-12-02
      • 2018-09-20
      • 2020-03-11
      相关资源
      最近更新 更多