Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

        }
like image 376
akirekadu Avatar asked Aug 10 '11 19:08

akirekadu


1 Answers

Try FileShare.ReadWrite | FileShare.Delete.

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

like image 192
Jordão Avatar answered Nov 07 '22 23:11

Jordão