使用C#删除文件夹(如果为空) [英] Delete Folder if it is Empty using C#

查看:388
本文介绍了使用C#删除文件夹(如果为空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个工具,使我可以浏览大量目录和子目录。如果它为空,我希望它删除一个文件夹。我可以使用以下代码删除空的文件夹和子文件夹:

I am writing a tool that will allow me to go though a fairly large list of Directories and Sub-directories. I would like it to delete a folder if there it is empty. I can delete folders and sub folders that are empty with this code:

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);
    }
}

我的问题是如何使代码通过每次删除后都要检查文件夹,因为一旦删除了一个文件夹,它可能会使父文件夹为空,因此应将其删除。一旦代码找不到任何为空的文件夹或子文件夹,便会退出。

My question is how to have the code go though and check the folders after each delete because once it deletes a folder it could make the parent folder empty and should then should be deleted. Once the code does not find any folders or sub-folders that are empty it would exit.

推荐答案

编写深度优先的递归功能。在完成每个递归调用时,请检查当前文件夹是否为空。如果是,则将其删除。

Write a depth-first recursive function. As you complete each recursive call, check the current folder to see if it is empty. If it is, then delete it.

类似这样的东西(伪代码)

Something like this (pseudocode)

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

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

这篇关于使用C#删除文件夹(如果为空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆