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?
I need to get the text in the file whenever the server changes it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With