FileSystemWatcher Changed event is raised twice

前端 未结 30 3318
死守一世寂寞
死守一世寂寞 2020-11-22 06:01

I have an application where I am looking for a text file and if there are any changes made to the file I am using the OnChanged eventhandler to handle the event

30条回答
  •  情话喂你
    2020-11-22 06:27

    Try this, It's working fine

      private static readonly FileSystemWatcher Watcher = new FileSystemWatcher();
        static void Main(string[] args)
        {
            Console.WriteLine("Watching....");
    
            Watcher.Path = @"D:\Temp\Watcher";
            Watcher.Changed += OnChanged;
            Watcher.EnableRaisingEvents = true;
            Console.ReadKey();
        }
    
        static void OnChanged(object sender, FileSystemEventArgs e)
        {
            try
            {
                Watcher.Changed -= OnChanged;
                Watcher.EnableRaisingEvents = false;
                Console.WriteLine($"File Changed. Name: {e.Name}");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            finally
            {
                Watcher.Changed += OnChanged;
                Watcher.EnableRaisingEvents = true;
            }
        }
    

提交回复
热议问题