FileSystemWatcher Changed event is raised twice

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

    In my case need to get the last line of a text file that is inserted by other application, as soon as insertion is done. Here is my solution. When the first event is raised, i disable the watcher from raising others, then i call the timer TimeElapsedEvent because when my handle function OnChanged is called i need the size of the text file, but the size at that time is not the actual size, it is the size of the file imediatelly before the insertion. So i wait for a while to proceed with the right file size.

    private FileSystemWatcher watcher = new FileSystemWatcher();
    ...
    watcher.Path = "E:\\data";
    watcher.NotifyFilter = NotifyFilters.LastWrite ;
    watcher.Filter = "data.txt";
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.EnableRaisingEvents = true;
    
    ...
    
    private void OnChanged(object source, FileSystemEventArgs e)
       {
        System.Timers.Timer t = new System.Timers.Timer();
        try
        {
            watcher.Changed -= new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = false;
    
            t.Interval = 500;
            t.Elapsed += (sender, args) => t_Elapsed(sender, e);
            t.Start();
        }
        catch(Exception ex) {
            ;
        }
    }
    
    private void t_Elapsed(object sender, FileSystemEventArgs e) 
       {
        ((System.Timers.Timer)sender).Stop();
           //.. Do you stuff HERE ..
         watcher.Changed += new FileSystemEventHandler(OnChanged);
         watcher.EnableRaisingEvents = true;
    }
    

提交回复
热议问题