0

A feature of this program basically needs to tail a log file and forward lines which are newly written to it. I believe I am doing this correctly by creating the FileStream with the FileShare.ReadWrite option as the stream for StreamReader, as described in several other answers here and here.

But when I run the program it prevents some processes from writing to the file. Using Process Monitor I can see that my program is opening the file with R/W rights instead of just Read.

reader = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

{
    //start at the end of the file
    long lastMaxOffset = reader.BaseStream.Length;

    while (true)
    {
        System.Threading.Thread.Sleep(Properties.Settings.Default.pauseInMilliseconds);

        // if the file size has not changed, keep idling
        if (reader.BaseStream.Length == lastMaxOffset)
            continue;

        // handle if the file contents have been cleared
        if (reader.BaseStream.Length < lastMaxOffset)
            lastMaxOffset = 0;
        eventLogger.WriteEntry("LogChipper target file was reset, starting from beginning", EventLogEntryType.Information, 0);

        // seek to the last max offset
        reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);

        // read out of the file until the EOF
        string line = "";
        while ((line = reader.ReadLine()) != null)
            syslogForwarder.Send(line);

        // update the last max offset
        lastMaxOffset = reader.BaseStream.Position;

        // block if the service is paused or is shutting down
        pause.WaitOne();
    }
}

Is there something else I'm doing in that block which is holding the file open? I'm open to trying different approaches (e.g. FileSystemWatcher) if that would be better...

Community
  • 1
  • 1
ewall
  • 27,179
  • 15
  • 70
  • 84
  • 2
    See http://stackoverflow.com/questions/4689904/fileshare-readwrite-not-working-c-net. It's likely to be the OTHER programs that are not opening the file in share mode. – Matthew Watson Feb 18 '13 at 20:03
  • FileShare.ReadWrite is R/W. – 500 - Internal Server Error Feb 18 '13 at 20:06
  • @500-InternalServerError : Looks to me like [System.IO.FileShare](http://msdn.microsoft.com/en-us/library/system.io.fileshare%28v=vs.90%29.aspx) is used for filtering what other processes can do with the file...? – ewall Feb 18 '13 at 21:00
  • @MatthewWatson : Thanks a good point, what if the other program is refusing to write to the file because it demands exclusive access? (I can edit the file in Notepad, it's just the other program that refuses to write once mine is watching the file.) I will investigate that angle further! – ewall Feb 18 '13 at 21:04

0 Answers0