How to get all the files, sub files and their size inside a directory in C#?

CsharpServer Side ProgrammingProgramming

To get the files, C# provides a method Directory.GetFiles

Directory.GetFiles returns the names of all the files (including their paths) that match the specified search pattern, and optionally searches subdirectories.

In the below example * is matches Zero or more characters in that position.

SearchOption TopDirectoryOnly. Searches only the top directories

SearchOption AllDirectories .Searches all the top directories and sub directories

FileInfo gets the file information like Length, name

Example 1

static void Main (string[] args) {
   string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";
   var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);

   foreach (string file in files) {
      Console.WriteLine(file);
   }
   Console.ReadLine ();
}

Output

C:\Users\Koushik\Desktop\TestFolder\TestFolderMain\TestFolderMain.txt
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1\TestFolderMain1.txt
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2\TestFolderMain2.txt
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2\TestFolderMainSubDirectory\TestFolderSubDirectory.txt

Example 2

static void Main (string[] args) {
   string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";
   var files = Directory.GetFiles(rootPath, "*.*", SearchOption.TopDirectoryOnly);

   foreach (string file in files) {
      Console.WriteLine(file);
   }
   Console.ReadLine ();
}

Output

C:\Users\Koushik\Desktop\TestFolder\Topdirectory.txt

Example 3

static void Main (string[] args) {
   string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";
   var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);

   foreach (string file in files) {
      var info = new FileInfo(file);
      Console.WriteLine($"{ Path.GetFileName(file) }: { info.Length } bytes");
   }
   Console.ReadLine ();
}

Output

Topdirectory.txt: 0 bytes
TestFolderMain.txt: 0 bytes
TestFolderMain1.txt: 10 bytes
TestFolderMain2.txt: 20 bytes
raja
Published on 25-Nov-2020 12:05:22
Advertisements