C# DirectoryInfo
Syntax
DirectoryInfo directory = new DirectoryInfo("path");
Example
Retrieve information about the contents of a directory using DirectoryInfo in C#.
DirectoryInfo directory = new DirectoryInfo(@"C:\Users\MyUser\MyDirectory");
foreach (var file in directory.GetFiles())
{
Console.WriteLine(file.Name);
}
foreach (var subDir in directory.GetDirectories())
{
Console.WriteLine(subDir.Name);
}
Output
File1.txt
File2.txt
Subdirectory1
Subdirectory2
Explanation
The DirectoryInfo
class in C# provides information about the contents of a directory. It represents an object that provides access to a directory and its contents.
To use DirectoryInfo
, you can create an instance of it by passing the path of the directory as a string to the constructor. The GetFiles()
and GetDirectories()
methods then return an array of file or folder names respectively.
In this example, we retrieve the contents of the directory "MyDirectory" and print the name of each file and folder inside it.
Use
DirectoryInfo
is useful when you need to obtain information about a directory and its contents. It allows you to retrieve the names of files and folders, as well as other information like creation time, modification time, and file size.
Important Points
DirectoryInfo
can be used to retrieve information about a directory and its contents.- You can create an instance of
DirectoryInfo
by passing the directory path to the constructor. GetFiles()
andGetDirectories()
return arrays of file or folder names, respectively.
Summary
DirectoryInfo
is a class in C# that provides information about the contents of a directory. It allows you to retrieve the names of files and folders, as well as other information like creation time, modification time, and file size. DirectoryInfo
is useful when you need to obtain information about a directory and its contents in your C# program.