Reputation: 5618
Code:
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(path, "*.exe");
fileSystemWatcher.IncludeSubdirectories = true;
fileSystemWatcher.Created += new FileSystemEventHandler(fileSystemWatcher_Created);
fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted);
fileSystemWatcher.EnableRaisingEvents = true;
The Created Event works fine, but the Deleted Event is only firing, when Deleting a Directory/or Exe with SHIFT. But normal-delete (moving to recycle bin) isn't working/firing the event!
How to solve the problem?
Upvotes: 8
Views: 9243
Reputation: 1
This one will Work.
FileSystemWatcher fsw = new FileSystemWatcher(folderPath);
fsw.Deleted+= FileSystem_Deleted;
fsw.EnableRaisingEvents = true;
fsw.IncludeSubdirectories = true;
static void FileSystem_Deleted(object sender, FileSystemEventArgs e)
{
// Write your code
MessageBox.Show("Deleted Item is " + e.name);
}
Upvotes: -1
Reputation: 4321
The solution is to use the following code:
private static void EnableFileWatcherLvl1(string folder, string fileName)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = folder;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Attributes;
watcher.Filter = "*.txt";
watcher.Changed += watcher_Changed;
watcher.Deleted += watcher_Changed;
watcher.EnableRaisingEvents = true;
}
static void watcher_Changed(object sender, FileSystemEventArgs e)
{
switch (e.ChangeType)
{
case WatcherChangeTypes.Changed: { // code here for created file }
break;
case WatcherChangeTypes.Deleted: { // code here for deleted file }
break;
}
}
Pay attention to the NotifyFilter
property, those are the filters it has to use. And this will trigger for Added
and Delete
files. I tested this in.Net Framework 4.5
.
Upvotes: 1
Reputation: 672
I know it's an old question, but I resolved this by adding FileName to the NotifyFilter property of the FileSystemWatcher object.
Upvotes: 15
Reputation: 25200
This is expected behaviour as the file isn't actually deleted: it's moved.
Try attaching to
filesystemWatcher.Renamed
and checking if the file is moved to the Recycle Bin instead.
Finding where the recycle bin actually is in the filesystem is not trivial, mind you. Some code posted by others (untried) is here: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/5d2be9aa-411c-4fd1-80f5-895f64aa672a/ - and also here: How can I tell that a directory is the recycle bin in C#?
Upvotes: 9