akirekadu
akirekadu

Reputation: 2357

Read a file in such a way that other processes are not prevented from modifying it

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);
            }

        }

Upvotes: 6

Views: 304

Answers (2)

Jordão
Jordão

Reputation: 56537

Try FileShare.ReadWrite | FileShare.Delete.

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

Upvotes: 3

Anders Abel
Anders Abel

Reputation: 69280

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.

Upvotes: 2

Related Questions