Andrew Simpson
Andrew Simpson

Reputation: 7324

Reading a file whilst being appended to by another thread

I am using C#. To illustrate my problem I simplified it to 2 timers on a WinForms Desktop application.

The first timer randomly selects an existing text file, opens it for appending to and writes a string to the end of it. It is then closed.
This process is called repeatedly every few milliseconds (or so).

The other timer also will randomly select a file and attempt to read it. This process is also called repeatedly every millisecond.

Eventually, the same file is addressed by both timers and I get a locking error.

Now i append to the file using these lines of code:

        using (FileStream stream = new FileStream(_folder + "\\manifest.log", FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
        {
            TextWriter newWriter = new StreamWriter(stream);
            newWriter.WriteLine(_timestamp);
            newWriter.Flush();
            newWriter.Close();
        }

and I read the file using these lines of code:

        using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan))
        using (var sr = new StreamReader(fs, Encoding.UTF8))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                yield return line;
            }
        }

The problem with the Share access is that it does not appear to work if i use 'Append'.
The problem with locking a file is that i will have no way of knowing before hand which file it will lock on as they are chosen randomly.

Before i look at redesigning my code for this i thought I would see if anyone had a clever idea on how to solve this.

thanks

Upvotes: 2

Views: 415

Answers (1)

Paul Farry
Paul Farry

Reputation: 4768

In your writer code, open with FileShare.Read, and in your reader could using FileShare.ReadWrite should suffice.

Have you tried simplifying your test. Just create 2 instances of your Filestreams. 1 Doing the write and then whilst still holding the file open create a 2nd Filestream that performs the read on the same file. Then you can verify that you have your sharing correct.

Upvotes: 1

Related Questions