递归搜索根目录和子文件夹中的文件

时间:2014-05-19 11:16:16

标签: c#

我需要在带有几个子目录的根文件夹上进行递归搜索,但我无法弄清楚如何在没有任何特定文件夹的情况下进行rootDirectory字符串搜索。我可以执行该文件,没有任何特定的根文件夹,如C:\ folder \ file。我需要的更像是RandomDirectory:\ randomsubfolder \ file没有特定的扩展名。

string rootDirectory = "";
    string extension = "";


    List<string> files = GetFilesRecursively (rootDirectory, extension);

    Console.WriteLine ("Got {0} files of extension {1} in directory {2}", files.Count, extension, rootDirectory);
    foreach (string file in files) {
        Console.WriteLine (file);
    }
}





static List<string> GetFilesRecursively (string rootDirectory, string extension) {

    if (!Directory.Exists (rootDirectory)) {

        return new List<string> ();
    }
    Console.WriteLine ("Currently in directory {0}", rootDirectory);


    List<string> opList = new List<string> ();


    string[] allFiles = Directory.GetFiles (rootDirectory, "" + extension);


    opList.AddRange (allFiles);


    string[] subDirectories = Directory.GetDirectories (rootDirectory);


    foreach (string subDir in subDirectories) {

        List<string> subDirFileList = GetFilesRecursively (subDir, extension);

        opList.AddRange (subDirFileList);
    }

1 个答案:

答案 0 :(得分:1)

string [] allfiles = Directory.GetFiles(path, "*", SearchOption.AllDirectories)