I am trying to constantly look at a log file that is deleted and overwritten when it is updated.
My current approach was to use FileSystemWatcher. This works fine when changing a file, but if I delete the file and create a new one with the same name, it will stop tracking it.
My current approach:
namespace LogReader
{
class Program
{
static void Main(string[] args)
{
Watch();
while (true)
{
}
}
public static void Watch()
{
var watch = new FileSystemWatcher();
watch.Path = @"C:\TEMP\test";
watch.Filter = "test.txt";
watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite;
watch.Changed += new FileSystemEventHandler(OnChanged);
watch.EnableRaisingEvents = true;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
if (e.FullPath == @"C:\TEMP\test\test.txt")
{
Console.Clear();
Stream stream = File.Open(@"C:\TEMP\test\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader streamReader = new StreamReader(stream);
var lines = streamReader.ReadToEnd();
Console.Out.WriteLine(lines);
streamReader.Close();
stream.Close();
}
}
}
}
source
share