C# Directory: A Complete Tutorial To Work With Directories in C#

Introduction

Folders on an operating system store files and sub-folders. The Directory class in C# and .NET provides functionality to work with folders. This article covers how to read a folder's properties, get the size and number of files of a folder, create a folder, create a subfolder, iterate through all files in a folder, move a folder, and delete a folder.

C# Directory class

C# Directory class in the .NET Framework 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.

using System.IO;

Create a Folder in C#

Directory.CreateDirectory method creates a directory or folder with the specified Windows security in the specified path. 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 exist already. Assuming the account running the code has admin permissions.

string root = @"C:\Temp";  
string subdir = @"C:\Temp\Mahesh";  
// If directory does not exist, create it.  
if (!Directory.Exists(root))  
{  
    Directory.CreateDirectory(root);  
}

Directory.CreateDirectory also creates a subdirectory or subfolder. All you have to do is to specify the path of the folder in which this subdirectory will be created. The following code snippet creates the 'Mahesh' subdirectory in the C:\Temp directory.

// Create sub directory  
if (!Directory.Exists(subdir))  
{  
    Directory.CreateDirectory(subdir);  
}

Delete a folder in C#

The Directory.Delete method deletes an empty folder from the specified path permanently. If a folder has subfolders and files, you must delete them before you can delete a folder. You will get an error message if you try to delete an empty file.

The following code snippet deletes the destination folder.

string root = @"C:\Temp";  
// If directory does not exist, don't even try  
if (Directory.Exists(root))  
{  
    Directory.Delete(root);  
}

The following code snippet checks if a directory has subdirectories and files and deletes them before deleting a directory.

Check if a folder Exists.

Directory.Exists method checks if the specified directory exists. The following code snippet checks whether a directory exists and deletes only if the directory exists.

string root = @"C:\Temp";  
// If directory does not exist, don't even try  
if (Directory.Exists(root))  
{  
    Directory.Delete(root);  
}

Move a folder in C#

Directory.Move method moves an existing directory to a new specified directory with a full path. The Move method takes two parameters. First, the Move method deletes the original directory.

The following code snippet moves the source directory to the destination directory.

string sourceDirName = @"C:\Temp";  
string destDirName = @"C:\NewTemp";  
try  
{  
    Directory.Move(sourceDirName, destDirName);  
}  
catch (IOException exp)  
{  
    Console.WriteLine(exp.Message);  
}

Copy a folder in C#

There is no method to copy a directory. Copying a directory is creating a new directory that you want a directory to move to and then copying the 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.

// Get and set file creation time  
string fileName = @"c:\temp\Mahesh.txt";  
File.SetCreationTime(fileName, DateTime.Now);  
DateTime dt = File.GetCreationTime(fileName);  
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 specified file's last access date and time. The following code snippet sets and gets a file's last access date and time.

// Get and set file last access time  
string fileName = @"c:\temp\Mahesh.txt";  
File.SetLastAccessTime(fileName,DateTime.Now);  
DateTime dt = File.GetLastAccessTime(fileName);  
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 specified file's last write date and time. The following code snippet sets and gets a file's last write date and time.

// Get and set file last write time  
string fileName = @"c:\temp\Mahesh.txt";  
File.SetLastWriteTime(fileName,DateTime.Now);  
DateTime dt = File.GetLastWriteTime(fileName);  
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.

string root = @"C:\Temp";  
// Get a list of all subdirectories  
var dirs = from dir in  
    Directory.EnumerateDirectories(root)  
             select dir;  
Console.WriteLine("Subdirectories: {0}", dirs.Count<string>().ToString());  
Console.WriteLine("List of Subdirectories");  
foreach (var dir in dirs)  
{  
    Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));  
}  
  
// Get a list of all subdirectories starting with 'Ma'  
var MaDirs = from dir in  
    Directory.EnumerateDirectories(root, "Ma*")  
             select dir;  
Console.WriteLine("Subdirectories: {0}", MaDirs.Count<string>().ToString());  
Console.WriteLine("List of Subdirectories");  
foreach (var dir in MaDirs)  
{  
    Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));  
}

Enumerate Files in C#

The Directory.The EnumerateFiles method returns an enumerable collection of file names in the specified directory.

string root = @"C:\Temp";  
// Get a list of all subdirectories  
var files = from file in  
Directory.EnumerateFiles(root)  
            select file;  
Console.WriteLine("Files: {0}", files.Count<string>().ToString());  
Console.WriteLine("List of Files");  
foreach (var file in files)  
{  
    Console.WriteLine("{0}", file);  
}

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.

string root = @"C:\Temp";  
// Get and Set Creation time  
Directory.SetCreationTime(root, DateTime.Now);  
DateTime creationTime = Directory.GetCreationTime(root);  
Console.WriteLine(creationTime);

Get and Set File Last Access Time

The SetLastAccessTime and GetLastAccessTime methods are used to set and get the specified directory's last access date and time. The following code snippet sets and gets a directory's last access date and time.

string root = @"C:\Temp";  
// Get and Set Last Access time  
Directory.SetLastAccessTime(root, DateTime.Now);  
DateTime lastAccessTime = Directory.GetLastAccessTime(root);  
Console.WriteLine(lastAccessTime);

Get and Set File Last Write Time

The SetLastWriteTime and GetLastWriteTime methods are used to set and get the specified directory's last write date and time. The following code snippet sets and gets a directory's last write date and time.

string root = @"C:\Temp";  
// Get and Set Last Write time  
Directory.SetLastWriteTime(root, DateTime.Now);  
DateTime lastWriteTime =Directory.GetLastWriteTime(root);  
Console.WriteLine(lastWriteTime);

Get and Set the Current Directory in C#

The SetCurrentDirectory method sets the specified directory as the current directory. The GetCurrentDirectory method returns the current directory.

string root = @"C:\Temp";   
Directory.SetCurrentDirectory(root);      
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.

public void GetSubDirectories()  
{  
    string root = @"C:\Temp";  
    // Get all subdirectories  
    string[] subdirectoryEntries = Directory.GetDirectories(root);  
    // Loop through them to see if they have any other subdirectories  
    foreach (string subdirectory in subdirectoryEntries)  
        LoadSubDirs(subdirectory);  
}  
private void LoadSubDirs(string dir)  
{  
    Console.WriteLine(dir);  
    string[] subdirectoryEntries = Directory.GetDirectories(dir);  
    foreach (string subdirectory in subdirectoryEntries)  
    {  
        LoadSubDirs(subdirectory);  
    }  
}

Get Files in a Directory in C#

The GetFiles method gets a list of files in the specified directory.

string root = @"C:\Temp";  
string[] fileEntries = Directory.GetFiles(root);  
foreach (string fileName in fileEntries);  
Console.WriteLine(fileName);

Get Root Directory in C#

The GetRootDirecoty method returns the root directory of the specified directory.

string root = @"C:\Temp";  
Console.WriteLine(Directory.GetDirectoryRoot(root));

Get all drives in C#

The GetLogicalDrives method returns all the logical drives on a system.

string[] drives = System.IO.Directory.GetLogicalDrives();  
foreach (string drive in drives)  
{  
    System.Console.WriteLine(drive);  
}

Summary

This article taught you how to work with the C# Directory class to create and get access to folders and files in C#


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.