Pregunta

I have a text file which is continuously getting updated from the server data.Now as per my requirement as soon as a new line gets written into the text file,I have to read this line and process it and repeat this to all the new lines getting written into the text file.For this i have to read the text file continuously.To the same i have tried to use FileSystemWatcher but later got to know that it will be very expensive and inefficient also. Now i am trying to read continuously using using FileShare.ReadWrite.Here is my code for the FileShare.ReadWrite mode..

if (System.IO.File.Exists(FileToCopy) == true)
{
    var fs = new FileStream(FileToCopy, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    using (var reader = new StreamReader(fs))
    {
        string line;
        string rawcdr;
        while (true)
        {
            while ((line = reader.ReadLine()) != null)
            {
            }
        }
    }
}

So i want to ask is it the right way to read a file continuously or it will stop once the file is finished? Will it watch the file continuously for new lines?

¿Fue útil?

Solución

Reader will stop at the end and close file (if you keep using in the code).

You can check file size and position reader (configured not to use BOM for Unicode encodings) to last read position via Reader.BaseStream (notice remarks about resetting inner buffers).

Note that both processes need to cooperate in picking open mode as if writer does not allow sharing you will have to read, reopen and seek instead.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top