Home  >  Article  >  Backend Development  >  How to get all files, subfiles and their sizes in a directory in C#?

How to get all files, subfiles and their sizes in a directory in C#?

WBOY
WBOYforward
2023-09-16 12:49:021564browse

How to get all files, subfiles and their sizes in a directory in C#?

In order to get files, C# provides a method Directory.GetFiles

Directory.GetFilesReturns the names of all files (including their paths) ) matches the specified search pattern and optionally searches subdirectories.

In the following example, * matches zero or more characters in that position.

SearchOption TopDirectoryOnly. Search only top-level directories

SearchOption AllDirectories. Search all top-level directories and subdirectories

FileInfo Get file length, name and other information

Example 1 H2>
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

The above is the detailed content of How to get all files, subfiles and their sizes in a directory in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Priority Queue in C#Next article:Priority Queue in C#