加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用C#删除文件夹为空

发布时间:2020-12-16 01:49:07 所属栏目:百科 来源:网络整理
导读:我正在编写一个工具,可以让我通过一个相当大的目录和子目录列表.我想删除一个文件夹,如果它是空的.我可以使用以下代码删除空的文件夹和子文件夹: string dir = textBox1.Text;string[] folders = System.IO.Directory.GetDirectories(dir,"*.*",System.IO.S
我正在编写一个工具,可以让我通过一个相当大的目录和子目录列表.我想删除一个文件夹,如果它是空的.我可以使用以下代码删除空的文件夹和子文件夹:

string dir = textBox1.Text;
string[] folders = System.IO.Directory.GetDirectories(dir,"*.*",System.IO.SearchOption.AllDirectories);
foreach (var directory in folders)
{
    if (System.IO.Directory.GetFiles(directory).Length == 0 && System.IO.Directory.GetDirectories(directory).Length == 0)
    {
        System.IO.StreamWriter Dfile = new System.IO.StreamWriter(newpath,true);
        System.IO.Directory.Delete(directory);
    }
}

我的问题是如何让代码通过,并在每次删除后检查文件夹,因为一旦删除文件夹,它可以使父文件夹为空,然后应该删除.一旦代码找不到任何空文件夹或子文件夹,它就会退出.

解决方法

编写深度优先递归函数.在完成每个递归调用时,请检查当前文件夹以查看它是否为空.如果是,则删除它.

像这样的东西(伪代码)

DeleteEmptyFolders(path)
{
  foreach Folder f in Path
  {
    DeleteEmptyFolders(f);

    if (f is empty)
    {
       Delete(f);
    }
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读