6

I need to continuously read a log file to detect certain patterns. How can do so without interfering with file operations that the log writer operation needs to perform?

The log writer process, in addition to writing logs, periodically moves the file to another location (one it reaches certain size).

With the way I read the file, the log writer app fails to move the file. I played with various FileShare options to no avail.

Here's simplified version of my code:

 using (FileStream stream = new FileStream(@"C:\temp\in.txt", FileMode.Open, FileAccess.Read, FileShare.Delete))
        { 
            TextReader tr = new StreamReader(stream);
            while (true)
            {

                Console.WriteLine(".. " + tr.ReadLine());
                Thread.Sleep(1000);
            }

        }
2
  • " the log writer app fails to move the file" -- you want to keep a reader open on a file that's getting moved? Aug 10, 2011 at 20:00
  • I want to keep reading as long as the file is available. I have no control over when/how the logging app moves the file. Ideally, I would get an exception when the file is moved and I start reading the new log file from that point on.
    – akirekadu
    Aug 10, 2011 at 21:21

2 Answers 2

3

Try FileShare.ReadWrite | FileShare.Delete.

But if the file is deleted (moved) then I think your reading will fail.

0
2

You are keeping the file open all the time, not only when there are changes to read.

I think a better approach would be to use a FileSystemWatcher to monitor the file for changes and then open the file when changed and read in the new data. If the file is only appended to, you can keep track of how long you have processed the file and immediately seek to that position when you've opened the file.

3
  • If this is a moderately (or heavily) used log file (which I suspect it might be) then this will trigger constantly. Say this file is getting written to it 1000 lines/second...
    – Joe
    Aug 10, 2011 at 20:03
  • @anders Then he has the same problem that maybe a writer want to move that file when a reader read.
    – Skomski
    Aug 10, 2011 at 20:16
  • Like Joe mentioned, this being a log file, gets updated constantly.
    – akirekadu
    Aug 10, 2011 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.