无法打开其他进程使用的文件 -

时间:2016-02-10 05:24:17

标签: c# file-io

我有一个读取大文本文件的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的答案 - 即使在那种情况下它实际上被另一个进程使用(即,我认为错误是假的)。 (所以不要把它标记为那个副本)我做错了什么?

1 个答案:

答案 0 :(得分:1)

pip install

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

请你试试

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);

请注意, File.Open 创建的FileStream对象会传递到 StreamReader