【问题标题】:C# How to select specific subdirectoryC#如何选择特定的子目录
【发布时间】:2016-03-28 01:55:37
【问题描述】:

我正在做类似于 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();
    }

【问题讨论】:

  • 请问有什么理由拒绝投票吗?
  • 我不会给你答案,而是向你解释这个概念。您需要递归地遍历每个目录以查找您要查找的内容。网上有很多例子,我建议你遵循(例如msdn.microsoft.com/en-us/library/bb513869.aspx)。祝你好运
  • 你真的认为我会检查所有这些吗?如果我现在放它,那甚至不可能使用递归,它只会一遍又一遍地向具有相同目录的控制台窗口发送垃圾邮件,直到我得到stackoverflowexception
  • 我只想跳过已经检查过的文件夹/子文件夹
  • 分享你的代码,我可以帮你。只问一般性问题,例如您不会收到任何回复,这很可能是您投反对票的原因!

标签: c# recursion cmd tree directory


【解决方案1】:

如果您想打印目录树,您可以使用递归而不获取任何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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多