删除FileSystemWatcher正在监视的文件夹

时间:2013-02-03 22:47:38

标签: c# directory

我想创建一个应用程序,而不是仅仅查看根层次结构文件夹,...我单独观看每个文件夹(关闭监视子文件夹)

但是,我似乎无法正确删除逻辑。我希望能够删除层次结构中的任何文件夹,无论是在应用程序内部还是外部,例如通过Windows资源管理器。

当我尝试其中任何一个时,看起来我遇到锁定问题,因为删除命令无法执行。

如果我禁用观看,那么一切似乎都有效。所以我假设问题是试图删除正在观看的文件夹。

有没有绕过这个?理想情况下,我希望fileSystemWatcher能够在其观看的文件夹被删除时自动停止观看。

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;

1 个答案:

答案 0 :(得分:0)

目前,您正在使用fsw1和fsw2来观看可能在任何时间删除的任何类型的数据。

虽然,我没有看到为每个文件夹创建FSW的重点,但这里的答案可能有所帮助:

为了观察文件夹本身,您需要为要观察的每个文件夹创建一个FSW。

然后,您可以按如下方式将FSW的NotifyFilter设置为DirectoryName:folderSystemWatcher.NotifyFilter = NotifyFilter.DirectoryName

查看此here的示例。

因此,其中一个FSW告诉您文件夹被删除,然后您可以停止,处置或对正在查看已删除文件夹的FSW执行任何操作。

我没有尝试过,但这就是我会怎么做的,我猜......

相关问题