FileSystemWatcher Changed event is raised twice

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

    The main reason was first event's last access time was current time(file write or changed time). then second event was file's original last access time. I solve under code.

            var lastRead = DateTime.MinValue;
    
            Watcher = new FileSystemWatcher(...)
            {
                NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
                Filter = "*.dll",
                IncludeSubdirectories = false,
            };
            Watcher.Changed += (senderObject, ea) =>
            {
                var now = DateTime.Now;
                var lastWriteTime = File.GetLastWriteTime(ea.FullPath);
    
                if (now == lastWriteTime)
                {
                    return;
                }
    
                if (lastWriteTime != lastRead)
                {
                    // do something...
                    lastRead = lastWriteTime;
                }
            };
    
            Watcher.EnableRaisingEvents = true;
    

提交回复
热议问题