This article will explain about the Directory class and its use. The System.IO namespace is one of the most significant namespaces used for working with directories in the .Net Framework. Let us see about the class.
Directory Class
The Directory class exposes many static methods for moving, copying, and deleting directories. There are static methods that involve creating, moving and deleting directories. Some of the most useful static methods of the Directory class are:
| S.No | Method | Description |
| 1 | CreateDirectory | This method is used to create a directory in the specified path. |
| 2 | Delete | This method is used to Delete a directory. |
| 3 | Exists | It returns whether the directory exists or not as Boolean result. |
| 4 | Move | Moves a specified directory to a new location. We can specify a different name for the file in the new location. |
| 5 | Getfiles | Return an array of files objects in the current directory. |
| 6 | GetDirectories | Returns an array of directory objects that represent the directories below the current directory. |
| 7 | GetCreationTime | Gets the creation date and time of a directory. |
CreateDirectory Method
This method is used to create a directory in the specified path.
|
public static void Main() { string dirpath = @"D:\Testdir"; try { if (Directory.Exists(dirpath)) { Console.WriteLine("That path exists already."); return; }
Directory.CreateDirectory(dirpath); Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(dirpath)); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } |
Delete Method
This method is used to Delete a directory.
|
public static void Main() { string dirpath = @"D:\Testdir"; try { Directory.Delete(dirpath); Console.WriteLine("The directory was deleted successfully."); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } |
Exists Method
It returns whether the directory exists or not as Boolean result.
|
string dirpath = @"D:\Testdir"; try { if (Directory.Exists(dirpath)) { Console.WriteLine("That path exists already."); return; } } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); }
|

Yesha sanghviPosted Jan 12, 2015, 10:20 AM
I Hope i will get it very soon..
Yesha sanghviPosted Jan 12, 2015, 10:20 AM
i want to examples of last 2 methods those are GetFiles() method and GetDirectories() method
Akemi ChouPosted Dec 22, 2013, 8:28 AM
but how can I create a directory that is default for Flash Drive?
pravin AmbekareditedPosted May 15, 2013, 1:42 AMEdited May 15, 2013, 1:42 AM
how can i create short cut of directory on desktop which is created programatilcally
Pradip PandeyPosted Jul 4, 2011, 8:56 AM
Good fundamental on directory handling in C#.