C# Directory Code Examples

The C# Directory class provides static methods for working with a directories and folders in C# such as get current working directory. The code examples in this tutorial show - How to create a folder in C#, delete a folder, read folder content, and move folder content using C# and .NET.

Working with Folders in C#

 
Folders on an operating system stores files. The Directory class in C# and .NET provides functionality to work with foldes. The functionality includes in this article covers, how to read a folder properties, get size and number of files of a folder, create a folder, create a sub folder, iterate through all files in a folder, move a folder, and delete a folder.
 
 Folders in C#
 

Directory class

 
The System.IO.Directory class in the .NET Framework class library provides static methods for creating, copying, moving, and deleting directories and subdirectories. Before you can use the Directory class, you must import the System.IO namespace.
  1. using System.IO;  

Create a Folder in C#

 
The Directory.CreateDirectory method creates a directory or folder in the specified path with the specified Windows security. You can also create a directory on a remote computer.
 
The following code snippet creates a Temp folder in C:\ drive if the directory does not exists already. Assuming the account running the code has admin permissions.
  1. string root = @"C:\Temp";  
  2. string subdir = @"C:\Temp\Mahesh";  
  3. // If directory does not exist, create it.  
  4. if (!Directory.Exists(root))  
  5. {  
  6.     Directory.CreateDirectory(root);  
  7. }  
The Directory.CreateDirectory is also creates a sub directory or sub folder. All you have to do is to specify the path of the folder in which this subdirectory will be created in. The following code snippet creates 'Mahesh' subdirectory in C:\Temp directory.
  1. // Create sub directory  
  2. if (!Directory.Exists(subdir))  
  3. {  
  4.     Directory.CreateDirectory(subdir);  
  5. }  

Delete a folder in C#

 
The Directory.Delete method deletes an empty folder from the specified path permanently. If a folder has sub folders and/or files, you must delete them before you can delete a folder. If you try to delete a file that is not empty, you will get an error message.
 
The following code snippet deletes the destination folder.
  1. string root = @"C:\Temp";  
  2. // If directory does not exist, don't even try  
  3. if (Directory.Exists(root))  
  4. {  
  5.     Directory.Delete(root);  
  6. }  
The following code snippet checks if a directory has subdirectories and files and delete them before deleting a directory.
 

Check if a folder Exists

 
The Directory.Exists method checks if the specified directory exists. The following code snippet checks if a directory exists or not and deletes only if the directory exists.
  1. string root = @"C:\Temp";  
  2. // If directory does not exist, don't even try  
  3. if (Directory.Exists(root))  
  4. {  
  5.     Directory.Delete(root);  
  6. }  

Move a folder in C#

 
The Directory.Move method moves an existing directory to a new specified directory with full path. The Move method takes two parameters. The Move method deletes the original directory.
 
The following code snippet moves the source directory to the destination directory.
  1. string sourceDirName = @"C:\Temp";  
  2. string destDirName = @"C:\NewTemp";  
  3. try  
  4. {  
  5.     Directory.Move(sourceDirName, destDirName);  
  6. }  
  7. catch (IOException exp)  
  8. {  
  9.     Console.WriteLine(exp.Message);  
  10. }  

Copy a folder in C#

 
There is no method to copy a directory. The copying a directory is a process of creating a new directory that you to want a directory to move to and then copying subdirectory and files.
 

Get and Set Directory Creation Time

 
The SetCreationTime and GetCreationTime methods are used to set and get the creation date and time of the specified file. The following code snippet sets and gets the creation time of a file.
  1. // Get and set file creation time  
  2. string fileName = @"c:\temp\Mahesh.txt";  
  3. File.SetCreationTime(fileName, DateTime.Now);  
  4. DateTime dt = File.GetCreationTime(fileName);  
  5. Console.WriteLine("File created time: {0}",dt.ToString());  

Get and Set File Last Access Time

 
The SetLastAccessTime and GetLastAccessTime methods are used to set and get the last access date and time of the specified file. The following code snippet sets and gets the last access date and time of a file.
  1. // Get and set file last access time  
  2. string fileName = @"c:\temp\Mahesh.txt";  
  3. File.SetLastAccessTime(fileName,DateTime.Now);  
  4. DateTime dt = File.GetLastAccessTime(fileName);  
  5. Console.WriteLine("File last access time: {0}", dt.ToString());  

Get and Set File Last Write Time

 
The SetLastWriteTime and GetLastWriteTime methods are used to set and get the last write date and time of the specified file. The following code snippet sets and gets the last write date and time of a file.
  1. // Get and set file last write time  
  2. string fileName = @"c:\temp\Mahesh.txt";  
  3. File.SetLastWriteTime(fileName,DateTime.Now);  
  4. DateTime dt = File.GetLastWriteTime(fileName);  
  5. Console.WriteLine("File last write time: {0}", dt.ToString());  

Enumerate Directory in C#

 
The Directory.EnumerateDirectories method returns an enumerable collection of directory names in the specified directory.
  1. string root = @"C:\Temp";  
  2. // Get a list of all subdirectories  
  3. var dirs = from dir in  
  4.     Directory.EnumerateDirectories(root)  
  5.              select dir;  
  6. Console.WriteLine("Subdirectories: {0}", dirs.Count<string>().ToString());  
  7. Console.WriteLine("List of Subdirectories");  
  8. foreach (var dir in dirs)  
  9. {  
  10.     Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));  
  11. }  
  12.   
  13. // Get a list of all subdirectories starting with 'Ma'  
  14. var MaDirs = from dir in  
  15.     Directory.EnumerateDirectories(root, "Ma*")  
  16.              select dir;  
  17. Console.WriteLine("Subdirectories: {0}", MaDirs.Count<string>().ToString());  
  18. Console.WriteLine("List of Subdirectories");  
  19. foreach (var dir in MaDirs)  
  20. {  
  21.     Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));  
  22. }  

Enumerate Files in C#

 
The Directory.EnumerateFiles method returns an enumerable collection of file names in the specified directory.
  1. string root = @"C:\Temp";  
  2.   
  3. // Get a list of all subdirectories  
  4. var files = from file in  
  5. Directory.EnumerateFiles(root)  
  6.             select file;  
  7. Console.WriteLine("Files: {0}", files.Count<string>().ToString());  
  8. Console.WriteLine("List of Files");  
  9. foreach (var file in files)  
  10. {  
  11.     Console.WriteLine("{0}", file);  
  12. }  

Get and Set File Creation Time

 
The Directory.SetCreationTime and Directory.GetCreationTime methods are used to set and get the creation date and time of the specified directory. The following code snippet sets and gets the creation time of a directory.
  1. string root = @"C:\Temp";  
  2. // Get and Set Creation time  
  3. Directory.SetCreationTime(root, DateTime.Now);  
  4. DateTime creationTime = Directory.GetCreationTime(root);  
  5. Console.WriteLine(creationTime);  

Get and Set File Last Access Time

 
The SetLastAccessTime and GetLastAccessTime methods are used to set and get the last access date and time of the specified directory. The following code snippet sets and gets the last access date and time of a directory.
  1. string root = @"C:\Temp";  
  2. // Get and Set Last Access time  
  3. Directory.SetLastAccessTime(root, DateTime.Now);  
  4. DateTime lastAccessTime = Directory.GetLastAccessTime(root);  
  5. Console.WriteLine(lastAccessTime);  

Get and Set File Last Write Time

 
The SetLastWriteTime and GetLastWriteTime methods are used to set and get the last write date and time of the specified directory. The following code snippet sets and gets the last write date and time of a directory.
  1. string root = @"C:\Temp";  
  2. // Get and Set Last Write time  
  3. Directory.SetLastWriteTime(root, DateTime.Now);  
  4. DateTime lastWriteTime =Directory.GetLastWriteTime(root);  
  5. Console.WriteLine(lastWriteTime);  

Get and Set Current Directory in C#

 
The SetCurrentDirectory method sets the specified directory as the current directory. The GetCurrentDirectory method returns the current directory.
  1. string root = @"C:\Temp";   
  2. Directory.SetCurrentDirectory(root);    
  3.      
  4. Console.WriteLine(Directory.GetCurrentDirectory());   

Get Sub Directories in C#

 
The GetDirectories method of the Directory class loads all the subdirectories of a directory. To get all subdirectories, we can read subdirectories recursively.
  1. public void GetSubDirectories()  
  2. {  
  3.     string root = @"C:\Temp";  
  4.     // Get all subdirectories  
  5.     string[] subdirectoryEntries = Directory.GetDirectories(root);  
  6.     // Loop through them to see if they have any other subdirectories  
  7.     foreach (string subdirectory in subdirectoryEntries)  
  8.         LoadSubDirs(subdirectory);  
  9. }  
  10. private void LoadSubDirs(string dir)  
  11. {  
  12.     Console.WriteLine(dir);  
  13.     string[] subdirectoryEntries = Directory.GetDirectories(dir);  
  14.     foreach (string subdirectory in subdirectoryEntries)  
  15.     {  
  16.         LoadSubDirs(subdirectory);  
  17.     }  
  18. }  

Get Files in a Directory in C#

 
The GetFiles method gets a list of files in the specified directory.
  1. string root = @"C:\Temp";  
  2. string[] fileEntries = Directory.GetFiles(root);  
  3. foreach (string fileName in fileEntries);  
  4. Console.WriteLine(fileName);  

Get Root Directory in C#

 
The GetRootDirecoty method returns the root directory of the specified directory.
  1. string root = @"C:\Temp";  
  2. Console.WriteLine(Directory.GetDirectoryRoot(root));  

Get all drives in C#

 
The GetLogicalDrives method returns all the logical drives on a system.
  1. string[] drives = System.IO.Directory.GetLogicalDrives();  
  2. foreach (string drive in drives)  
  3. {  
  4.     System.Console.WriteLine(drive);  
  5. }