Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file used by another process [duplicate]

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.

like image 925
Christoffer Avatar asked Mar 18 '12 15:03

Christoffer


People also ask

How do you copy a file while it is being used by another process?

To create a copy of a file that is read- and/or write-locked by another process on Windows, the simplest (and probably only) solution is to use the Volume Shadow Copy Service (VSS). The Volume Shadow Copy Service is complex and difficult to call from managed code.


1 Answers

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.

like image 124
Hans Passant Avatar answered Oct 09 '22 04:10

Hans Passant