I had a situation recently in which I needed to display in my application the log file that was being generated by the application which was using log4net. Any time I tried to open the log file I would get an exception because the file was in use. I searched google for the answer as I normally do and found many others trying to find the same exact answer. Some came up with ideas like copying the original file to another temporary file and opening it. Others seemed to reach a dead end. However I soon figured out what my issue was.
When reading my file using StreamReader it appears that while I assumed since I was reading the file it should not be an issue if it was in use since I was only reading it. Well that is were I was making my wrong assumption. It appears that the StreamReader object opens the file and tries to set an exclusive lock on the file while reading the contents. Since in my case another program already has an exclusive lock it would fail.
So I started to look at how I could open the file in truly a read only mode. While I found people talking again about opening a file in use for readonly access it was for some reason not clear to me what the exact solution was.
So what is the solution? System.IO.FileShare
By creating a FileStream object and setting FileShare.ReadWrite I am saying that I want to open the file in a mode that allows other files to Read and Write to/from the file while I have it opened.
Here is an example code snipet of how I read my log file that was currently in use by the logging object log4net. Hope this helps someone else.
private void LoadFile()
{
try
{
using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}
}
catch(Exception ex)
{
MessageBox.Show("Error loading log file: " + ex.Message);
}
}