1

I'm trying to code a program which will watch a directory/disk and move deleted files/folders to recycle bin when they are deleted from network shared folder.

I have this code which is working when a file/folder is deleted but I need to cancel delete and move file to Recycle Bin. I found how to move file/folder to Recycle Bin here: How to Move files to the recycle bin

FileSystemWatcher fsw = new FileSystemWatcher();

private void frmMain_Load(object sender, EventArgs e)
{
    StartWatcher("X:\\Virtuals\\");
}
private void StopWatcher()
{
    if (fsw != null)
        try
        {
            fsw.EnableRaisingEvents = false;
            fsw.Dispose();
            fsw = null;
        }
        catch { }
}
private void StartWatcher(string path)
{
    StopWatcher();

    FileSystemWatcher fsw = new FileSystemWatcher();
    fsw.Path = Path.GetDirectoryName(path);
    fsw.Filter = Path.GetFileName(path);
    fsw.NotifyFilter = NotifyFilters.LastAccess |
    NotifyFilters.LastWrite | NotifyFilters.FileName
    | NotifyFilters.DirectoryName;
    fsw.Deleted += new FileSystemEventHandler(OnDeleted);
    fsw.EnableRaisingEvents = true;
}
private void OnDeleted(object source, FileSystemEventArgs e)
{ MessageBox.Show("File deleted: " + e.FullPath); }
Community
  • 1
  • 1
HasanG
  • 12,734
  • 29
  • 100
  • 154

2 Answers2

3

FileSystemWatcher won't help you in your task. Proper way to do this is employ a filesystem filter driver which will intercept file deletion requests and move files to the recycle bin instead. You can create your own filter driver (requires knowledge of low-level kernel-mode development), or we offer CallbackFilter product which lets you do the job in user mode (even in .NET).

Eugene Mayevski 'Callback
  • 45,135
  • 8
  • 71
  • 121
1

The FileSystemWatcher raises events after the file is actually deleted, modified or created, so it´s to late to do a copy after the delete event is raised. And there is no possibility to cancel an operation with the FileSystemWatcher. Possibly it can be solved by using some sort of low level APIs (but I don´t know which and how).

Espen Burud
  • 1,871
  • 10
  • 9