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;