C # is constantly looking at the recovered file

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();
            }
        }

    }
}
+4
source share
2 answers

This is because Create and Delete operations will not trigger an event OnChangedin the FileSystemWatcher file. Therefore, you need to register these events and assign the same event handler. OnChangedIt will look like this:

 watch.Created += new FileSystemEventHandler(OnChanged);
 watch.Deleted += new FileSystemEventHandler(OnChanged);

FileSystemWatcher.

+4

, . .

    public static void Watch()
    {
        var watch = new FileSystemWatcher();
        watch.Path = @"C:\TEMP\test";
        watch.Filter = "test.txt";
        watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.CreationTime; //more options
        watch.Created += new FileSystemEventHandler(OnChanged);
        watch.Changed += new FileSystemEventHandler(OnChanged);
        watch.EnableRaisingEvents = true;
    }
+1

All Articles