In C#, DirectoryInfo Class is a part of System.IO namespace and it provides properties and methods to perform various operations on directory and subdirectory such as to create, delete and move directory. It cannot be inherited.
C# DirectoryInfo Properties
The following tables list the properties provided by DirectoryInfo class.
Property | Description |
---|---|
CreationTime | It is used to get or set the creation time of the current file or directory. |
Exists | This property provides a value indicating whether the directory exists or not. |
Extension | It is used to get the extension part of the file. |
Name | It is used to get the name of this DirectoryInfo instance. |
FullName | This property provides the full path of a directory. |
LastAccessTime | It is used to gets or sets the time the current file or directory was last accessed. |
Parent | It is useful to get the parent directory of a specified subdirectory. |
C# DirectoryInfo Methods
Method | Description |
---|---|
Create() | It creates a directory. |
Delete() | It deletes the specified directory. |
EnumerateDirectories() | It returns an enumerable collection of directory information in the current directory. |
GetDirectories() | Returns the subdirectories of the current directory. |
GetFiles() | Returns the file list from the current directory. |
MoveTo() | It moves a specified directory and its contents to a new path. |
ToString() | It returns the original path that was passed by the user. |
Example: C# program for DirectoryInfo Class
The program is used to create a directory in C#.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | using System; using System.IO; namespace FileExample { class Program { static void Main(string[] args) { string fLoc = "Sample"; DirectoryInfo dir = new DirectoryInfo(fLoc); // checking for its existence if (dir.Exists) { Console.WriteLine("The Directory already exists."); } else { // creating directory dir.Create(); Console.WriteLine("Directory Created Successfully!"); } } } } |
Output:
Directory Created Successfully!
A directory named “Sample” will be created on a path that you will specify in a program. The program also checks if the directory specified already exists in that path or not.
Example: C# program for DirectoryInfo Class tp delete a directory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using System; using System.IO; namespace FileExample { class Program { static void Main(string[] args) { string fLoc = "sample.text"; DirectoryInfo dir = new DirectoryInfo(fLoc); try { dir.Delete(); Console.WriteLine("Directory Deleted Successfully!"); } catch (Exception ex) { Console.WriteLine("Something is wrong: " + ex.ToString()); } } } } |
Output:
Directory Deleted Successfully!