Searching for subdirectories within a given directory is a common task in many applications. In C#, we can use the Directory and DirectoryInfo classes provided by the System.IO namespace to perform this task. In this article, we will explore how to write a C# program to search subdirectories within a given directory.
The easiest way to search for subdirectories within a given directory is to use the DirectoryInfo.GetDirectories() method. This method returns an array of DirectoryInfo objects that represent the directories in the specified directory.
Here's how we use the DirectoryInfo.GetDirectories() method to search for subdirectories in a given directory -
using System.IO; using System; class Program { static void Main(string[] args) { string path = @"C:\Users\JohnDoe\Documents"; DirectoryInfo directory = new DirectoryInfo(path); foreach (DirectoryInfo subdirectory in directory.GetDirectories()) { Console.WriteLine(subdirectory.FullName); } } }
In this code, we first specify the directory path to search in a string variable named path. Then we create a new DirectoryInfo object to represent the directory.
Next, we use the DirectoryInfo.GetDirectories() method to get an array of DirectoryInfo objects that represent the subdirectories in the directory.
Finally, we use a foreach loop to loop through the array of subdirectory objects and print the full name of each subdirectory to the console.
Another way to search for subdirectories within a given directory is to use the Directory.GetDirectories() method. This method returns an array of strings representing the names of subdirectories within the specified directory.
Here's how we use the Directory.GetDirectories() method to search for subdirectories within a given directory -
using System; using System.IO; class Program { static void Main() { string path = @"C:\Users\JohnDoe\Documents"; string[] subdirectories = Directory.GetDirectories(path); foreach (string subdirectory in subdirectories) { Console.WriteLine(subdirectory); } } }
In this code, we first specify the directory path to search in a string variable named path. We then use the Directory.GetDirectories() method to get an array of strings representing the names of subdirectories within the directory.
Finally, we use a foreach loop to loop through the array of subdirectory names and print each name to the console.
In this article, we explored how to write a C# program to search for subdirectories within a given directory using the Directory and DirectoryInfo classes provided by the System.IO namespace. We learned how to use DirectoryInfo.GetDirectories() method and Directory.GetDirectories() method to search for subdirectories in a given 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 to search subdirectories within a given directory. For more information, please follow other related articles on the PHP Chinese website!