GeekZilla
Reading a file which is locked by another process
The following code snippet shows how to read a file which is locked by another process..
FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader logFileReader = new StreamReader(logFileStream); while (!logFileReader.EndOfStream) { string line = logFileReader.ReadLine(); // Your code here } // Clean up logFileReader.Close(); logFileStream.Close();
Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.
Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.
Comments
Steve
said:
This doesn't work, try a file locked by the OS or an SQL Server mdf file
Karthik
said:
It does not work. I have a file locked by OS as well.
Rob
said:
It worked for me. I'm reading Log Files generated by IIS.
I had the same code as in the example with the excepetion of FileShare mode. I used FileShare.Write but changed it now to FileShare.ReadWrite.
thanks..
Rob
Ferret
said:
Worked for me, MS documents. Thanks!
Francesco
said:
Thanks it works.
Brad
said:
The code worked great for me! Still do not understand why setting access to read did not while read/write did.........
Almost resorted to copyinng the file prior to reading and a plan'C'-bringing in some scripting.
Thanks for your help
-BM
Sigi
said:
Thanks a lot. Works great for me. My log file is locked by a pipe process.
Hans
said:
Worked for me too. Reading locked IIS logfiles..
Thanks!
Corey
said:
Thanks Paul. This worked great for a log file locked by Log4Net DLL.
Leo
said:
I looked for this everywhere and all efforts failed. This one worked. The only difference here is the last argument of the FileStream constructor call, the "FileShare.ReadWrite" specification.
Thank you sir.
Just to clarify, I am talking about files locked by MS Excel.
It is a shame I cannot get the ReadAllText method to work this way, it complains with locked files.
Piotr
said:
This code does not solve problem reading already locked file. If you try to open file that is already locked you will get exception!! This code allow to open not locked file in share mode Read/Write so other processes can access it.
Kumar Kolli
said:
Really useful. Thanks!