C# Program to Search Directories and List Files


Searching directories and listing files is a common task in many applications. In C#, we can use the Directory and File classes provided by the System.IO namespace to perform these tasks. In this article, we will explore how to write a C# program to search directories and list files.

Method: Using Directory.GetFiles()

The simplest way to search directories and list files in C# is by using the Directory.GetFiles() method. This method returns an array of strings that represents the paths of all files in a specified directory that match a specified search pattern.

Here's how we can use the Directory.GetFiles() method to list all the files in a directory −

Example

using System.IO;
using System;

class Program {
   static void Main() {
      string path = @"C:\Users\JohnDoe\Documents";
      string[] files = Directory.GetFiles(path);
   
      foreach (string file in files) {
         Console.WriteLine(file);
      }
   }
}

In this code, we start by specifying the directory path that we want to search in a string variable named path. We then use the Directory.GetFiles() method to get an array of strings that represent the paths of all files in the directory.

Finally, we use a foreach loop to iterate through the array of file paths and print each path to the console.

Method: Using Directory.EnumerateFiles()

Another way to search directories and list files in C# is by using the Directory.EnumerateFiles() method. This method returns an enumerable collection of strings that represents the paths of all files in a specified directory that match a specified search pattern.

Here's how we can use the Directory.EnumerateFiles() method to list all the files in a directory −

Example

using System.IO;
using System;

class Program {
   static void Main(string[] args) {
      string path = @"C:\Users\JohnDoe\Documents";
   
      foreach (string file in Directory.EnumerateFiles(path)) {
         Console.WriteLine(file);
      }
   }
}

In this code, we start by specifying the directory path that we want to search in a string variable named path. We then use the Directory.EnumerateFiles() method to get an enumerable collection of file paths.

Finally, we use a foreach loop to iterate through the collection of file paths and print each path to the console.

Conclusion

In this article, we explored how to write a C# program to search directories and list files using the Directory and File classes provided by the System.IO namespace. We learned how to use the Directory.GetFiles() method and the Directory.EnumerateFiles() method to list all the files in a specified directory. Both methods are efficient and easy to use, making them essential tools for any C# developer.

Updated on: 04-May-2023

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements