user316117
user316117

Reputation: 8281

Cannot open a file used by another process -

I have a C# program that reads in a big text file. The old version of the file used some VBNet calls . . .

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

which were archaic and causing problems by interpreting commas as EOL's, so I decided to replace them with System.IO calls . . .

        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)
        {
     . . . 

But I'm getting "The process cannot access the file 'C:\Users\Peter\WorkAtHome\nChain.txt' because it is being used by another process." But I don't get that error in the old version of the code that used the VBNet calls. And I don't get it in Notepad where I can read it and write it! And I have no evidence the file is actually being used by another process. I based my syntax on the answers to Reading a file used by another process - even though it that case it actually was being used by another process (i.e, I think the error is spurious). (so don't flag this as a duplicate of that one) What am I doing wrong?

Upvotes: 0

Views: 1340

Answers (1)

bkdev
bkdev

Reputation: 432

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

The problem here could be because the first line (File.Open) is already keeping the file open when you are attempting to read it again in second line using StreamReader(sPath)

Could you please try

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
    }
}

Please note here that the FileStream object created by File.Open is passed on to the StreamReader.

Upvotes: 1

Related Questions