C#如何选择特定的子目录

时间:2015-12-21 22:00:09

标签: c# recursion cmd tree directory

我正在做类似于cmd树的事情。我计划首先检查C:\比检查其中的第一个文件夹,如果第一个文件夹中包含的东西,请检查它,依此类推,直到我得到DirectoryNotFoundException。如果我得到这样的话我想跳过第一个文件夹并检查第二个文件夹怎么做?

static string path = @"C:\";
    static void Main()
    {
        try
        {
            DirectoryInfo di = new DirectoryInfo(path);
            DirectoryInfo[] fileNames = di.GetDirectories();
        }
        catch (DirectoryNotFoundException)
        {
            DirectoryInfo di = new DirectoryInfo(path);
            DirectoryInfo[] fileNames = di.GetDirectories();
            //i need to edit the picking of filenames.Something like PickSecond/Next
        }

        Console.ReadKey();
    }

1 个答案:

答案 0 :(得分:0)

如果要打印目录树,可以使用递归而不获取任何DirectoryNotFoundException。以下代码将从特定路径开始向控制台打印所有子目录。递归以这种方式工作:每次找到一个文件夹,如果它不是空的,那么去探索它的子目录,否则去检查下一个文件夹。

static void DirectoryTree(string directory, string indent = "")
{
    try
    {
        DirectoryInfo currentDirectory = new DirectoryInfo(directory);
        DirectoryInfo[] subDirectories = currentDirectory.GetDirectories();

        // Print all the sub-directories in a recursive way.
        for (int n = 0; n < subDirectories.Length; ++n)
        {
            // The last sub-directory is drawn differently.
            if (n == subDirectories.Length - 1)
            {
                Console.WriteLine(indent + "└───" + subDirectories[n].Name);
                DirectoryTree(subDirectories[n].FullName, indent + "    ");
            }
            else
            {
                Console.WriteLine(indent + "├───" + subDirectories[n].Name);
                DirectoryTree(subDirectories[n].FullName, indent + "│   ");
            }
        }
    }
    catch (Exception e)
    {
        // Here you could probably get an "Access Denied" exception,
        // that's very likely if you are exploring the C:\ folder.
        Console.WriteLine(e.Message);
    }
}

static void Main()
{
    // Consider exploring a more specific folder. If you just type "C:\"
    // you are requesting to view all the folders in your computer.
    var path = @"C:\SomeFolder" ;
    Console.WriteLine(path);
    if(Directory.Exists(path))
        DirectoryTree(path);
    else
    Console.WriteLine("Invalid Directory");
    Console.ReadKey();
}