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
Author Paul Hayman

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 ( and is also the creator of GeekZilla.


Steve said:

This doesn't work, try a file locked by the OS or an SQL Server mdf file

04/Dec/2007 09:04 AM

Karthik said:

It does not work. I have a file locked by OS as well.

17/Dec/2007 16:33 PM

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.



26/Jan/2008 22:30 PM

Ferret said:

Worked for me, MS documents. Thanks!

03/Sep/2008 05:54 AM

Francesco said:

Thanks it works.

12/Dec/2008 09:22 AM

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


17/Apr/2009 03:10 AM

Sigi said:

Thanks a lot. Works great for me. My log file is locked by a pipe process.

08/Dec/2009 09:25 AM

Hans said:

Worked for me too. Reading locked IIS logfiles..


05/Feb/2010 19:41 PM

Corey said:

Thanks Paul. This worked great for a log file locked by Log4Net DLL.

08/Apr/2010 16:01 PM

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.

21/Jun/2011 11:33 AM

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.

10/Sep/2012 19:29 PM

Kumar Kolli said:

Really useful. Thanks!

26/Feb/2013 18:01 PM

Add Comment


Your comment has been received and will be shown once it passes moderation.