Lectura de un archivo mientras otro subproceso lo adjunta

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

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.


preguntado el 09 de septiembre de 13 a las 08:09

1 Respuestas

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.

Respondido el 09 de Septiembre de 13 a las 08:09

Good morning, I should obviously check my code before posting! I have FileShare.Read set to FileShare.Write. - what a dunce i am! - Andrew Simpson

don't beat yourself up, you asked a legitimate question - pablo farry

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.