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

前端 未结 22 2525
长发绾君心
长发绾君心 2020-11-22 00:07

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

22条回答
  •  死守一世寂寞
    2020-11-22 00:49

    In .NET 4.5, at least, there's this version that is much shorter and has the added bonus of evaluating any file criteria for inclusion in the list:

    public static IEnumerable GetAllFiles(string path, 
                                                  Func checkFile = null)
    {
        string mask = Path.GetFileName(path);
        if (string.IsNullOrEmpty(mask)) mask = "*.*";
        path = Path.GetDirectoryName(path);
        string[] files = Directory.GetFiles(path, mask, SearchOption.AllDirectories);
    
        foreach (string file in files)
        {
            if (checkFile == null || checkFile(new FileInfo(file)))
                yield return file;
        }
    }
    

    Use like this:

    var list = GetAllFiles(mask, (info) => Path.GetExtension(info.Name) == ".html").ToList();
    

提交回复
热议问题