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

本文关键字:文件 文件夹 搜索 根目录 递归 | 更新日期: 2023-09-27 18:04:14

我需要对具有几个子目录的根文件夹进行递归搜索,但我无法弄清楚,如何在没有任何特定文件夹的情况下进行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);
    }

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

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