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...