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

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

    This one helped me to get all files in a directory and sub directories, May be helpful for someone. [ Inspired from above answers ]

    static void Main(string[] args)
        {
            try
            {
                var root = @"G:\logs";
                DirectorySearch(root);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }
    
    
    
    
    
    public static void DirectorySearch(string root, bool isRootItrated = false)
    {
        if (!isRootItrated)
        {
            var rootDirectoryFiles = Directory.GetFiles(root);
            foreach (var file in rootDirectoryFiles)
            {
                Console.WriteLine(file);
            } 
        }
    
        var subDirectories = Directory.GetDirectories(root);
        if (subDirectories?.Any() == true)
        {
            foreach (var directory in subDirectories)
            {
                var files = Directory.GetFiles(directory);
                foreach (var file in files)
                {
                    Console.WriteLine(file);
                }
                DirectorySearch(directory, true);
            }
        }
    }
    

提交回复
热议问题