Question:
Is it posible to detect when a file, for wich a have an open FileStream, was renamed.
Case:
I am trying to monitor the logs for our application, I read from the logfiles since I do not want to interfere with the logging itself.
This works great until the file gets rolled. My application keeps reading from a renamed file without even noticing.
I tried using a FileSystemWatcher to detect the roll, but sometimes a get a lot of events, sometimes I don't, so that's not really a good solution (also the logfiles could reside on a network share wich could be an extra hold-back for using a FSW).
If I could find out which file(name) I have an open handle to, I could compare that to the _fileName
but I don't know how or if this can be done.
Are there any other options I could explore?
Code:
this is a simplified version of my filemonitoring class:
public class MonitorFile
{
private String _fileName = String.Empty;
private bool _stopMonitoring = false;
public MonitorFile(string fileName)
{
_fileName = fileName;
}
// Simplified method
public void StartMonitoring()
{
using (var reader = new StreamReader(
new FileStream(
_monitorFileName,
FileMode.Open,
FileAccess.Read,
FileShare.Delete | FileShare.ReadWrite)))
{
while (!_stopMonitoring)
{
Thread.Sleep(500);
while ((line = reader.ReadLine()) != null)
{
//...Do stuff with the lines
}
}
}
}
}