Home >Backend Development >C#.Net Tutorial >C# program for searching directories and listing files
Searching directories and listing files are common tasks 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'll explore how to write a C# program to search directories and list files.
The easiest way to search a directory and list files in C# is to use the Directory.GetFiles() method. This method returns an array of strings representing the paths to all files in the specified directory that match the specified search pattern.
This is how we can list all the files in a directory using the Directory.GetFiles() method -
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 first specify the directory path to search by specifying a string variable named path. We then use the Directory.GetFiles() method to get an array of strings representing the paths to all files in the directory.
Finally, we use a foreach loop to iterate over the array of file paths and print each path to the console.
In C#, another way to search a directory and list files is to use the Directory.EnumerateFiles() method. This method returns an enumerable collection of strings representing the paths to all files in the specified directory that match the specified search pattern.
Here's how we use the Directory.EnumerateFiles() method to list all files in a directory -
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 first specify the directory path 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.
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 files in a specified directory. Both methods are efficient and easy to use, making them essential tools for any C# developer.
The above is the detailed content of C# program for searching directories and listing files. For more information, please follow other related articles on the PHP Chinese website!