-1

How can I retrieve all the files in a directory that has files, sub-folders, and files in that folders.

NOTE: The folder/files is not constant

Ramil Aliyev 007
  • 4,437
  • 2
  • 31
  • 47
xSynaptic
  • 3
  • 2

2 Answers2

2

You can use the DirectoryInfo.GetFiles method with the RecurseSubdirectories option.

using System.IO;

FileInfo[] files 
    = new DirectoryInfo(@"C:\Program Files")
    .GetFiles("*", new EnumerationOptions { RecurseSubdirectories = true });

If you don't need the full list of files, it may be faster to enumerate the directory's contents.

using System.IO;
using System.Collections.Generic;
using System.Linq;

var directory = new DirectoryInfo(@"C:\Program Files");
IEnumerable<FileInfo> files 
    = from file in directory.EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true })
      where file.Name = "target.txt"
      select file;

foreach (FileInfo file in files)
{
    //...
}
                           
D M
  • 5,769
  • 4
  • 12
  • 27
1

You can use Directory.GetFiles(path) and Directory.GetDirectories(path)

static void ScanDir(string path, int spaces = 0)
{
    var files = Directory.GetFiles(path);
    foreach (var file in files)
    {
        for (int i = 0; i < spaces; i++)
            Console.Write(" "); // Just for styling

        Console.WriteLine(file);
    }

    var dirs = Directory.GetDirectories(path);
    foreach (var dir in dirs)
    {
        ScanDir(dir, spaces + 4);
    }
}


static void Main()
{
    ScanDir("C:\\path\\to");
}
isaque
  • 158
  • 5