如何在C#中递归列出目录中的所有文件? [英] How to recursively list all the files in a directory in C#?

查看:37
本文介绍了如何在C#中递归列出目录中的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#中递归列出目录和子目录中的所有文件?

How to recursively list all the files in a directory and child directories in C#?

推荐答案

本文涵盖了所有你需要.除了搜索文件和比较名称之外,只需打印名称即可.

This article covers all you need. Except as opposed to searching the files and comparing names, just print out the names.

可以这样修改:

static void DirSearch(string sDir)
{
    try
    {
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string f in Directory.GetFiles(d))
            {
                Console.WriteLine(f);
            }
            DirSearch(d);
        }
    }
    catch (System.Exception excpt)
    {
        Console.WriteLine(excpt.Message);
    }
}

由 barlop 添加

GONeale 提到上面没有列出当前目录中的文件,并建议将文件列表部分放在获取目录的部分之外.以下将做到这一点.它还包括一个您可以取消注释的 Writeline 行,它有助于跟踪您在递归中的位置,这可能有助于显示调用以帮助显示递归的工作原理.

GONeale mentions that the above doesn't list the files in the current directory and suggests putting the file listing part outside the part that gets directories. The following would do that. It also includes a Writeline line that you can uncomment, that helps to trace where you are in the recursion that may help to show the calls to help show how the recursion works.

            DirSearch_ex3("c:\aaa");
            static void DirSearch_ex3(string sDir)
            {
                //Console.WriteLine("DirSearch..(" + sDir + ")");
                try
                {
                    Console.WriteLine(sDir);

                    foreach (string f in Directory.GetFiles(sDir))
                    {
                        Console.WriteLine(f);
                    }

                    foreach (string d in Directory.GetDirectories(sDir))
                    {
                        DirSearch_ex3(d);
                    }
                }
                catch (System.Exception excpt)
                {
                    Console.WriteLine(excpt.Message);
                }
            }

这篇关于如何在C#中递归列出目录中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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