【问题标题】:Deleting the folder being watched by FileSystemWatcher删除 FileSystemWatcher 正在监视的文件夹
【发布时间】:2013-01-18 15:40:10
【问题描述】:

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

但是,我似乎无法正确获取删除逻辑。我希望能够删除层次结构中的任何文件夹,无论是在应用程序内部还是外部,例如通过 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;

【问题讨论】:

  • 你的意思是当它即将被删除时停止观看?
  • 只是先处理观察者,继续下去没有意义。观察文件夹被删除需要观察父目录。
  • @TonyHopkinson,我想是的,是的。

标签: c# directory


【解决方案1】:

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

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

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

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

查看here 的示例。

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

我没有尝试过,但我想这就是我应该这样做的方式......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2013-09-09
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2020-09-21
    相关资源
    最近更新 更多