Curriculum
DirectoryInfo is a class in C# that provides information about a directory and allows you to perform operations on the directory, such as creating or deleting files and directories, and enumerating the files and directories within it. Here’s an example of using DirectoryInfo to list the files in a directory:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Create a DirectoryInfo object for the directory we want to list
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:UsersJohnDoeDocuments");
// Check if the directory exists
if (!directoryInfo.Exists)
{
Console.WriteLine("Directory not found!");
return;
}
// Enumerate the files in the directory and display their names
foreach (FileInfo fileInfo in directoryInfo.GetFiles())
{
Console.WriteLine(fileInfo.Name);
}
}
}
In this example, we first create a DirectoryInfo object for the directory we want to list. We then check if the directory exists by calling the Exists property of the DirectoryInfo object. If the directory does not exist, we display an error message and return from the method.
Next, we use the GetFiles method of the DirectoryInfo object to get an array of FileInfo objects that represent the files in the directory. We then use a foreach loop to enumerate the files in the directory and display their names using the Name property of the FileInfo object.
It’s important to note that DirectoryInfo provides many other useful properties and methods for working with directories, such as CreateSubdirectory to create a new subdirectory, Delete to delete a directory, GetDirectories to enumerate the subdirectories within a directory, and Parent to get the parent directory of a directory.