在目录中搜索文件递归 [英] Searching for file in directories recursively

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

问题描述

我有以下的code通过目录,这将返回所有XML文件的名单给我的文件进行递归搜索。一切运作良好,但在根目录不包括在列表中的XML文件。

I have the following code to recursively search for files through a directory, which returns a list of all xml files to me. All works well, except that xml files in the root directory are not included in the list.

我明白为什么,因为它所做的第一件事就是让在根目录,然后得到的文件,从而错过了的GetFiles()的调用根。我想包括的GetFiles之前的foreach()调用,但结果并不如我所料。

I understand why, since the first thing it does is get the directories in the root, then get files, thus missing the GetFiles() call on the root. I tried including the GetFiles() call prior to the foreach, but the results are not as I expect.

public static ArrayList DirSearch(string sDir)
{
    try
    {
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string f in Directory.GetFiles(d, "*.xml"))
            {
                string extension = Path.GetExtension(f);
                if (extension != null && (extension.Equals(".xml")))
                {
                fileList.Add(f);
                }
            }
            DirSearch(d);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return fileList;
}

我的目录结构是这样的:

My directory structure is something like:

RootDirectory
        test1.0.xml
            test1.1.xml
            test1.2.xml
  2ndLevDir
            test2.0.xml
            test2.1.xml
  3rdLevDir
               test3.0.xml
               test3.1.xml

code回报:

Code returns:

test2.0.xml
test2.1.xml
test3.0.xml
test3.1.xml

我想回每个文件包括:

I would like to return every file including:

test1.0.xml
test1.1.xml
test1.2.xml

不太好诗句用递归。任何指针将大大AP preciated。

Not very well verse with recursion. Any pointers would be greatly appreciated.

推荐答案

您可以使用这种超负荷 Directory.GetFiles 它搜索子目录你。

You could use this overload of Directory.GetFiles which searches subdirectories for you.

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

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