FileSystemWatcher Changed event is raised twice

前端 未结 30 3715
死守一世寂寞
死守一世寂寞 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:29

    Try with this code:

    class WatchPlotDirectory
    {
        bool let = false;
        FileSystemWatcher watcher;
        string path = "C:/Users/jamie/OneDrive/Pictures/Screenshots";
    
        public WatchPlotDirectory()
        {
            watcher = new FileSystemWatcher();
            watcher.Path = path;
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Filter = "*.*";
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);
            watcher.EnableRaisingEvents = true;
        }
    
    
    
        void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (let==false) {
                string mgs = string.Format("File {0} | {1}",
                                           e.FullPath, e.ChangeType);
                Console.WriteLine("onchange: " + mgs);
                let = true;
            }
    
            else
            {
                let = false;
            }
    
    
        }
    
        void OnRenamed(object sender, RenamedEventArgs e)
        {
            string log = string.Format("{0} | Renamed from {1}",
                                       e.FullPath, e.OldName);
            Console.WriteLine("onrenamed: " + log);
    
        }
    
        public void setPath(string path)
        {
            this.path = path;
        }
    }
    

提交回复
热议问题