Reading a file used by another process

Christoffer picture Christoffer · Mar 18, 2012 · Viewed 63.8k times · Source

I am monitoring a text file that is being written to by a server program. Every time the file is changed the content will be outputted to a window in my program.

The problem is that I can't use the Streamreader on the file as it is being used by another process. Setting up a Filestream with ReadWrite won't do any good since I cannot control the process that is using the file.

I can open the file in notepad. It must be possible to access it even though the server is using it.

Is there a good way around this?

Should I do the following?

  1. Monitor the file
  2. Make a temp copy of it when it changes
  3. Read the temp copy
  4. Delete the temp copy.

I need to get the text in the file whenever the server changes it.

Answer

Hans Passant picture Hans Passant · Mar 18, 2012

If notepad can read the file then so can you, clearly the program didn't put a read lock on the file. The problem you're running into is that StreamReader will open the file with FileShare.Read. Which denies write access. That can't work, the other program already gained write access.

You'll need to create the StreamReader like this:

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.Default)) {
    // read the stream
    //...
}

Guessing at the Encoding here. You have to be careful with this kind of code, the other program is actively writing to the file. You won't get a very reliable end-of-file indication, getting a partial last line is quite possible. In particular troublesome when you keep reading the file to try to get whatever the program appended.