Eric Bergman-Terrell's Blog

How to Programmatically Read a Locked Log4Net Log File
November 6, 2007

I recently added log4net logging to this website. After configuring log4net and adding logging code the the web application, I immediately added a page to my administration site to display the log. Unfortunately, the initial code I wrote threw an exception because, not surprisingly, the log4net log file was locked.

The trick is to open the file in FileShare.ReadWrite mode:


protected string logFileText;

protected void Page_Load(object sender, EventArgs e)
    string path = Server.MapPath("~/logs/log.txt");

    using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (StreamReader streamReader = new StreamReader(fileStream))
        logFileText = streamReader.ReadToEnd();

Keywords: Log4Net, logging, software development, .NET, file locking

Reader Comments

LinusThe solution provided by Sunil is not the same and will not solve the same issues, as "MinimalLock" can still lock the file, as I already had that set and needed to stream.
 December 19, 2014
Sunil SharmaI found a better method to do this at: 18, 2009
mr mOThank you sooo very much!
http://mokhan.caJuly 24, 2008

Comment on this Blog Post

Recent Posts

EBTCalc Users: A Desktop Version is Now Available!October 25, 2019
Python Script to Audit MediaMonkey TranscodingAugust 15, 2019
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016