Share via


System.IO.File.ReadAllLines() : File already in use

Question

Wednesday, March 25, 2009 6:34 PM

Hi,

I'm trying to open a file using the System.IO.File.ReadAllLines() method.

But when I try to run it, I get the following error :

System.IO.IOException :
The process cannot access the file 'c:\..' because it is being used by another process.

Ok, but i just need to read its contents, I don't need to modify it.  Is there a way I can open it in read only mode even if its locked by another process.  After all, I can open it with notepad, so there must be a way to read its content!

Thanks

Daniel

All replies (8)

Wednesday, March 25, 2009 9:04 PM âś…Answered | 2 votes

Solution found...  I needed to add a FileShare.ReadWrite on the Stream.  Works like a charm now...

System.IO.FileStream fs = new System.IO.FileStream(txtFilePath.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.FileShare.ReadWrite);  
 
System.IO.StreamReader sr = new System.IO.StreamReader(fs);  
 
List<String> lst = new List<string>();  
 
while (!sr.EndOfStream)  
     lst.Add(sr.ReadLine());  
 

 


Wednesday, March 25, 2009 7:00 PM

Try the StreamReader object I don't think it cares if it is open or not. You will still want to catch any exceptions so you can exit gracefully if the file is locked.


Wednesday, March 25, 2009 7:13 PM

Unfortunately, I get the exact same error with that line of code :

System.IO.FileStream fs = new System.IO.FileStream(txtFilePath.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read);


Wednesday, March 25, 2009 7:19 PM

That means that the file has been locked even for reading by the process that opened it. Other than shadow copying or doing something like Unlocker does, I don't know that there is a way around that.


Wednesday, March 25, 2009 8:49 PM

What do you mean by "shadow copying?"  A copy of the file on the hard drive? 

How come any other program like NotePad, TextPad, PSPad can open it then?  There must be a way to do it :/

Daniel


Wednesday, March 25, 2009 9:15 PM

I'm glad you found it, I didn't read your construction code thouroughly enough. Sorry.


Wednesday, March 25, 2009 10:10 PM

Hang on one sec. One moment you had this problem with File.ReadAllLines() and you solved it with using a StreamReader to iterate through the file line by line?

Yes, I know that will solve the issue, particularly if you surrounded the StreamReader with a using block, but that really is a bandaid to determine what caused the problem in the first place.

Were you doing other IO stuff before you called File.ReadAllLines()?

John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com


Friday, November 9, 2012 4:24 AM

Use FileAccess.ReadWrite, it will work.