【问题标题】:Cannot open a file used by another process -无法打开另一个进程使用的文件 -
【发布时间】:2016-02-10 22:50:34
【问题描述】:

我有一个读取大文本文件的 C# 程序。该文件的旧版本使用了一些 VBNet 调用。 . .

  ff = VBNET.FileSystem.FreeFile();
  VBNET.FileSystem.FileOpen(ff, sPath, VBNET.OpenMode.Input, VBNET.OpenAccess.Default, VBNET.OpenShare.Default, -1);
  while (!(VBNET.FileSystem.EOF(ff)))   //  )start       Do Until EOF(tf);
  {
      VBNET.FileSystem.Input(ff, ref sMyString);
. . .

这是过时的,并且通过将逗号解释为 EOL 引起问题,所以我决定用 System.IO 调用替换它们。 . .

        System.IO.File.Open(sPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); 
        System.IO.StreamReader file = new System.IO.StreamReader(sPath);
        while ((sMyString = file.ReadLine()) != null)
        {
     . . . 

但我收到 “该进程无法访问文件 'C:\Users\Peter\WorkAtHome\nChain.txt',因为它正被另一个进程使用。” 但在使用 VBNet 调用的旧版本代码中,我没有收到该错误。而且我无法在记事本中读取它并写入它!而且我没有证据表明该文件实际上正在被另一个进程使用。我的语法基于Reading a file used by another process 的答案——即使在这种情况下它实际上正被另一个进程使用(即,我认为错误是虚假的)。 (所以不要将此标记为与那个重复)我做错了什么?

【问题讨论】:

    标签: c# file-io


    【解决方案1】:
    System.IO.File.Open(sPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); 
    System.IO.StreamReader file = new System.IO.StreamReader(sPath);
    

    这里的问题可能是因为当您尝试使用 StreamReader(sPath) 在第二行再次读取文件时,第一行 (File.Open) 已经保持文件打开

    你可以试试

    using(FileStream fs = System.IO.File.Open(sPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
    {
        using(System.IO.StreamReader filesr = new System.IO.StreamReader(fs))
        {
            //read from streamreader
        }
    }
    

    这里请注意,File.Open 创建的 FileStream 对象被传递给 StreamReader

    【讨论】:

    • 不;在第一个 using 语句的行上产生相同的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多