簡體   English   中英

如何等待直到包含文件的目錄在C#中被遞歸刪除

[英]How to wait until directories having files get deleted recursively in C#

我要刪除幾個包含很多文件的文件夾。 然后,我再次創建這些文件夾。 現在的問題是,有時目錄刪除需要花費一些時間。

但是在創建目錄之前,請檢查目錄是否存在。 因此,這里出現的問題是它已經存在並且不再創建目錄。

if (Directory.Exists(path))
            {

                Directory.Delete(path, true);
            }
 if (!Directory.Exists(path))
            {

                dir = Directory.CreateDirectory(path);
                dir.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
            }

我會使用文件監視程序。 看到這里:[ https://www.infoworld.com/article/3185447/how-to-work-with-filesystemwatcher-in-c.html]

他們文章中但針對您的問題進行了修改的代碼是:

using System;
using System.IO;

namespace FileWatcherExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"c:\example";
            MonitorDirectory(path);
            Console.ReadKey();
        }

        private static void MonitorDirectory(string path)
        {
            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
            fileSystemWatcher.Path = path;
            fileSystemWatcher.Deleted += (o,s) => Console.WriteLine("File deleted: {0}", e.Name);
            fileSystemWatcher.EnableRaisingEvents = true;
        }
    }
}

文件觀察器允許創建,修改和刪除事件,使您可以永久獲取對文件夾或文件所做更改的實時更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM