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

前端 未结 22 2393
长发绾君心
长发绾君心 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:42

    A simple and clean solution

    /// 
    /// Scans a folder and all of its subfolders recursively, and updates the List of files
    /// 
    /// Full path of the folder
    /// The list, where the output is expected
    internal static void EnumerateFiles(string sFullPath, List fileInfoList)
    {
        try
        {
            DirectoryInfo di = new DirectoryInfo(sFullPath);
            FileInfo[] files = di.GetFiles();
    
            foreach (FileInfo file in files)
                fileInfoList.Add(file);
    
            //Scan recursively
            DirectoryInfo[] dirs = di.GetDirectories();
            if (dirs == null || dirs.Length < 1)
                return;
            foreach (DirectoryInfo dir in dirs)
                EnumerateFiles(dir.FullName, fileInfoList);
    
        }
        catch (Exception ex)
        {
            Logger.Write("Exception in Helper.EnumerateFiles", ex);
        }
    }
    

提交回复
热议问题