tags:

views:

82

answers:

5

Hi,

I have a small problem. I have a tool which should parse a log file daily, unfortunatetly this log file is in use by the process which writes to the log and I cannot stop it.

First try was to create a copy of the file, which is not working either.

Is there any way for me to read the current text of the log file, even if it is already in use?

A: 

I highly recommend BareTail, which we use to look at all of our logs in real time. Also supports highlighting, which is very useful.

Dave
hmmm... looks like OP wants a programmatic way to read the file when it's already open. =P
Dave
+2  A: 

Use File.OpenRead(path), this allows you to access a readonly stream to the file; that way you won't be bothered if another application has a write lock on the file.

Jan Jongboom
+1  A: 

it depends, have you tried reading the file in read only? using one of the static methods

 System.IO.File.ReadAllText(path) or  System.IO.File.ReadAllLines(path)

they may work if there file isn't locked exclusively

Pharabus
+2  A: 

You are at the mercy of the program that is writing the file. In Windows, a process can open a file for reading, writing or both, but it can also control whether other processes can open the file for reading, writing or both. If the other process has denied you the right to read the contents of the file, then there is nothing you can do about it.

If you control the source code of the program that is writing the log file, then change it to allow read access by other processes.

Christian Hayter
+1  A: 
using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        while (!reader.EndOfStream)
        {

        }
    }
}

The FileAccess specifies what YOU want to do with the file. The FileShare specifies what OTHERS can do with the file while you have it in use.

In the example above, you can open a file for reading while other processes can have the file open for read/write access. In most cases, this will work for opening logfiles that are in use.

Tom Vervoort
+1, the only correct answer here. Specifying FileShare.ReadWrite is crucial. The other process has already gained Write access, you cannot deny it.
Hans Passant
Thanks, that worked perfectly!
Feroc
File.OpenRead does this within.
Jan Jongboom
No it doesn't. Take a look with reflector: return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
Tom Vervoort
Yes, File.OpenRead did not work for me
Feroc