简体   繁体   中英

FileSystemWatcher - Windows Explorer->Undo

I'm developing an application in which I'm using a FileSystemWatcher for watching file/directory creation/deletion events using the NotifyFilters.FileName and NotifyFilters.DirectoryName filters. I also set IncludeSubdirectories to true

Using this, if I copy a folder in windows explorer, I get creation events for every sub item of that new folder as well as the new folder itself. However, if I delete a folder in windows explorer (that contains sub items), and then "undo" that operation in windows explorer, I only get a creation event for the folder, not any of the sub items.

I can't simply do a Directory.GetFiles() as the sub items may not exist at that point, and I can't just dispatch it to a later time as depending on the count/size of files, the undo operation may take a long time to complete and I won't know how long to delay the dispatch.

I've noticed that if I also listen to the NotifyFilters.Attributes flag, then I do get a ResourceChanged event for each and every subitem of an undo operation, but the ResourceChanged event gets raised for lots of other situations, and I'm really looking for a definitive creation event.

Any suggestions?

If you delete a file in explorer the file is moved to Recycle Bin. If the file is restored from recycle bin you can detect it by adding a watcher to the recycle bin. Finding the path of the recycle bin is a bit tricky, but this code does the work:

WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
string path = string.Format(@"C:\$Recycle.Bin\{0}", currentUser.User.Value);
FileSystemWatcher w = new FileSystemWatcher(path, "*.*");
w.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Attributes | NotifyFilters.Size;
w.IncludeSubdirectories = true;
w.Changed += watcher_Changed;
w.Created += watcher_Created;
w.Renamed += watcher_Renamed;
w.Deleted += watcher_Deleted;
w.EnableRaisingEvents = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM