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

前端 未结 22 2394
长发绾君心
长发绾君心 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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:33

    Here is a version of B. Clay Shannon's code not static for excel-files:

    class ExcelSearcher
    {
        private List<string> _fileNames;
    
        public ExcelSearcher(List<string> filenames)
        {
            _fileNames = filenames;
        }
        public List<string> GetExcelFiles(string dir, List<string> filenames = null)
        {
    
            string dirName = dir;
            var dirNames = new List<string>();
            if (filenames != null)
            {
                _fileNames.Concat(filenames);
            }
            try
            {
                foreach (string f in Directory.GetFiles(dirName))
                {
                    if (f.ToLower().EndsWith(".xls") || f.ToLower().EndsWith(".xlsx"))
                    {
                        _fileNames.Add(f);
                    }
                }
                dirNames = Directory.GetDirectories(dirName).ToList();
                foreach (string d in dirNames)
                {
                    GetExcelFiles(d, _fileNames);
                }
            }
            catch (Exception ex)
            {
                //Bam
            }
            return _fileNames;
        }
    
    0 讨论(0)
  • 2020-11-22 00:34

    I prefer to use DirectoryInfo because I can get FileInfo's, not just strings.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection<FileInfo> matchingFileInfos = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Select(x => x)
                .ToList();
    

    I do this in case in the future I need future filtering..based on the properties of FileInfo.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection<FileInfo> matchingFileInfos = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Where(x => x.LastWriteTimeUtc < DateTimeOffset.Now)
                .Select(x => x)
                .ToList();
    

    I can also resort back to strings if need be. (and still am future proofed for filters/where-clause stuff.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection<string> matchingFileNames = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Select(x => x.FullName)
                .ToList();
    

    Note that "." is a valid search pattern if you want to filer by extension.

    0 讨论(0)
  • 2020-11-22 00:34

    If you only need filenames and since I didn't really like most of the solutions here (feature-wise or readability-wise), how about this lazy one?

    private void Foo()
    {
      var files = GetAllFiles("pathToADirectory");
      foreach (string file in files)
      {
          // Use can use Path.GetFileName() or similar to extract just the filename if needed
          // You can break early and it won't still browse your whole disk since it's a lazy one
      }
    }
    
    /// <exception cref="T:System.IO.DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
    /// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
    /// <exception cref="T:System.IO.IOException"><paramref name="path" /> is a file name.-or-A network error has occurred.</exception>
    /// <exception cref="T:System.IO.PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters and file names must be less than 260 characters.</exception>
    /// <exception cref="T:System.ArgumentNullException"><paramref name="path" /> is null.</exception>
    /// <exception cref="T:System.ArgumentException"><paramref name="path" /> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="F:System.IO.Path.InvalidPathChars" />.</exception>
    [NotNull]
    public static IEnumerable<string> GetAllFiles([NotNull] string directory)
    {
      foreach (string file in Directory.GetFiles(directory))
      {
        yield return file; // includes the path
      }
    
      foreach (string subDir in Directory.GetDirectories(directory))
      {
        foreach (string subFile in GetAllFiles(subDir))
        {
          yield return subFile;
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 00:35
    IEnumerable<string> GetFilesFromDir(string dir) =>
     Directory.EnumerateFiles(dir).Concat(
     Directory.EnumerateDirectories(dir)
              .SelectMany(subdir => GetFilesFromDir(subdir)));
    
    0 讨论(0)
  • 2020-11-22 00:37

    In Framework 2.0 you can use (It list files of root folder, it's best the most popular answer):

    static void DirSearch(string dir)
    {
        try
        {
            foreach (string f in Directory.GetFiles(dir))
                Console.WriteLine(f);
            foreach (string d in Directory.GetDirectories(dir))
            {
                Console.WriteLine(d);
                DirSearch(d);
            }
    
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    
    0 讨论(0)
提交回复
热议问题