3

I'd like to create an application where instead of only watching a root hierarchy folder, ... I watch each folder individually (with watch subfolders turned off)

However, I can't seem to be able to get the delete logic right. I want to be able to delete any folder in the hierarchy, either internally within the application, or externally, say via windows explorer.

When I try either of these, it appears I get locking issues, as the delete commands fail to execute.

If I disable the watching, then everything seems to work. So I'm assuming the problem is trying to delete a folder that is being watched.

Is there anyway of getting around this? I'd ideally like the fileSystemWatcher to automatically stop watching when the folder its watching has been deleted.

public MainWindow()
{
    InitializeComponent();

    fsw1 = new FileSystemWatcher()
    {
        Path = "Folder",
        NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.FileName | NotifyFilters.DirectoryName,
        IncludeSubdirectories = false,
        Filter = "",
        EnableRaisingEvents = true
    };

    fsw1.Deleted += new FileSystemEventHandler(OnFileSystemItemDeleted);

    fsw2 = new FileSystemWatcher()
    {
        Path = "Folder/Folder",
        NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.FileName | NotifyFilters.DirectoryName,
        IncludeSubdirectories = false,
        Filter = "",
        EnableRaisingEvents = true
    };

    fsw2.Deleted += new FileSystemEventHandler(OnFileSystemItemDeleted);
}

protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
    base.OnMouseLeftButtonDown(e);

    //fsw1.EnableRaisingEvents = false;
    //fsw2.EnableRaisingEvents = false;

    System.IO.Directory.Delete("Folder", true);
}

void OnFileSystemItemDeleted(object sender, FileSystemEventArgs e)
{

}

FileSystemWatcher fsw1, fsw2;
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hammer
  • 145
  • 1
  • 10

1 Answers1

0

Currently, you are using fsw1 and fsw2 in order to watch data of any type that might get deleted at any point of time.

Although, i do not see the point of creating a FSW for each folder, here is an answer that might help:

In order to watch for the folders themselves, you need to create a FSW for each folder you would like to observe.

You can then setup the NotifyFilter of the FSW to DirectoryName as follows: folderSystemWatcher.NotifyFilter = NotifyFilter.DirectoryName

see an example of this here.

So one of the FSWs tell you that a folder is deleted, you can then stop, dispose or do whatever to the FSW that is watching that deleted folder.

I did not try that out, but this is how i would have done it, i guess...

Community
  • 1
  • 1
Rustom Aburas
  • 17
  • 1
  • 5