【问题标题】:File Read-only access irrespective of locks (C#)文件只读访问,与锁无关 (C#)
【发布时间】:2023-03-05 22:21:02
【问题描述】:

如何打开(使用 c#)已经打开的文件(例如在 MS Word 中)?我想如果我打开文件进行读取访问,例如

FileStream f= new FileStream('filename', FileMode.Open, FileAccess.ReadWrite);

我应该成功,但我得到一个异常:

"进程无法访问文件 因为它被锁定了......”

我知道必须有一种方法来读取文件,而不管文件上是否加了任何锁,因为我可以使用 Windows 资源管理器复制文件或使用记事本等其他程序打开它,即使它在 WORD 中打开也是如此。

但是,C# 中的文件 IO 类似乎都不允许我这样做。为什么?

【问题讨论】:

    标签: c# io


    【解决方案1】:

    您想设置 FileAccess=Read 和 FileShare=ReadWrite。这是一篇很棒的文章(以及对原因的​​解释):

    http://coding.infoconex.com/post/2009/04/How-do-I-open-a-file-that-is-in-use-in-C.aspx

    【讨论】:

      【解决方案2】:

      您的代码正在使用 FileAccess.Read*Write* 标志。尝试阅读。

      【讨论】:

      • 对不起,我实际上是在使用 FileAccess.Read
      【解决方案3】:

      我知道这是一篇旧帖子。但我需要这个,我认为这个答案可以帮助其他人。

      以资源管理器的方式复制锁定的文件。

      尝试使用此扩展方法获取锁定文件的副本。

      使用示例

      private static void Main(string[] args)
          {
              try
              {
                  // Locked File
                  var lockedFile = @"C:\Users\username\Documents\test.ext";
      
                  // Lets copy this locked file and read the contents
                  var unlockedCopy = new 
                  FileInfo(lockedFile).CopyLocked(@"C:\Users\username\Documents\test-copy.ext");
      
                  // Open file with default app to show we can read the info.
                  Process.Start(unlockedCopy);
              }
              catch (Exception ex)
              {
                  Trace.TraceError(ex.Message);
              }
          }
      

      扩展方法

      internal static class LockedFiles
      {
          /// <summary>
          /// Makes a copy of a file that was locked for usage in an other host application.
          /// </summary>
          /// <returns> String with path to the file. </returns>
          public static string CopyLocked(this FileInfo sourceFile, string copyTartget = null)
          {
              if (sourceFile is null)
                  throw new ArgumentNullException(nameof(sourceFile));
              if (!sourceFile.Exists)
                  throw new InvalidOperationException($"Parameter {nameof(sourceFile)}: File should already exist!");
      
              if (string.IsNullOrWhiteSpace(copyTartget))
                  copyTartget = Path.GetTempFileName();
      
              using (var inputFile = new FileStream(sourceFile.FullName, FileMode.Open, 
              FileAccess.Read, FileShare.ReadWrite))
              using (var outputFile = new FileStream(copyTartget, FileMode.Create))
                  inputFile.CopyTo(outputFile, 0x10000);
      
              return copyTartget;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多