Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# FileSystemWatcher.Deleted not Firing on "normal" deleting?

Tags:

c#

.net

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?

like image 621
eMi Avatar asked Nov 08 '11 09:11

eMi


3 Answers

I know it's an old question, but I resolved this by adding FileName to the NotifyFilter property of the FileSystemWatcher object.

like image 122
AlbertVanHalen Avatar answered Oct 15 '22 08:10

AlbertVanHalen


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#?

like image 25
Jeremy McGee Avatar answered Oct 15 '22 08:10

Jeremy McGee


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.

like image 33
Joe Almore Avatar answered Oct 15 '22 07:10

Joe Almore