C# DirectoryInfo
last modified April 20, 2025
This tutorial explains how to use the DirectoryInfo class in C# to perform directory operations. DirectoryInfo provides methods for creating, moving, and enumerating directories.
The DirectoryInfo class exposes instance methods for creating, moving, and enumerating through directories and subdirectories. It provides more functionality than the static Directory class.
DirectoryInfo
is useful when you need to perform multiple operations
on the same directory. It caches information about the directory, improving
performance for repeated operations.
Creating a DirectoryInfo Instance
This example demonstrates how to create a DirectoryInfo instance and check if a directory exists. The DirectoryInfo constructor takes a directory path.
using System; using System.IO; class Program { static void Main() { string path = @"C:\Temp\TestDirectory"; DirectoryInfo dirInfo = new DirectoryInfo(path); if (dirInfo.Exists) { Console.WriteLine($"Directory '{path}' already exists."); } else { Console.WriteLine($"Directory '{path}' does not exist."); } } }
The code creates a DirectoryInfo instance for the specified path. It then checks if the directory exists using the Exists property. The DirectoryInfo constructor accepts a string representing the path to a directory.
The Exists property returns true if the directory exists, false otherwise. This example shows the basic way to initialize DirectoryInfo and check directory existence. Note that the path uses the @ verbatim string literal to avoid escaping backslashes.
Creating and Deleting Directories
This example shows how to create and delete directories using DirectoryInfo. The Create and Delete methods handle these operations.
using System; using System.IO; class Program { static void Main() { string path = @"C:\Temp\NewDirectory"; DirectoryInfo dirInfo = new DirectoryInfo(path); if (!dirInfo.Exists) { dirInfo.Create(); Console.WriteLine($"Directory '{path}' created successfully."); } // Perform operations on the directory dirInfo.Delete(); Console.WriteLine($"Directory '{path}' deleted successfully."); } }
The Create method makes a new directory at the specified path. The Delete method removes the directory. The example first checks if the directory exists using the Exists property. If not, it creates the directory using the Create method.
After performing any needed operations, it deletes the directory with the Delete method. Note that Delete will throw an exception if the directory doesn't exist or isn't empty. For non-empty directories, use Delete(true) for recursive deletion.
Getting Directory Properties
DirectoryInfo provides properties to access directory information. This example shows how to retrieve various directory properties.
using System; using System.IO; class Program { static void Main() { DirectoryInfo dirInfo = new DirectoryInfo(@"C:\Temp"); Console.WriteLine($"Full Name: {dirInfo.FullName}"); Console.WriteLine($"Name: {dirInfo.Name}"); Console.WriteLine($"Parent: {dirInfo.Parent}"); Console.WriteLine($"Root: {dirInfo.Root}"); Console.WriteLine($"Creation Time: {dirInfo.CreationTime}"); Console.WriteLine($"Last Access Time: {dirInfo.LastAccessTime}"); Console.WriteLine($"Last Write Time: {dirInfo.LastWriteTime}"); Console.WriteLine($"Attributes: {dirInfo.Attributes}"); } }
The example displays various directory properties including name, parent, creation time, and attributes. FullName returns the complete path of the directory. Name returns just the directory name portion of the path.
Parent returns the parent directory, and Root returns the root portion of the path. The time-related properties show when the directory was created, last accessed, and last modified. Attributes returns the file system attributes of the directory.
Enumerating Files and Directories
DirectoryInfo provides methods to enumerate files and subdirectories. This example shows how to list all files and directories in a given path.
using System; using System.IO; class Program { static void Main() { DirectoryInfo dirInfo = new DirectoryInfo(@"C:\Temp"); Console.WriteLine("Files:"); foreach (FileInfo file in dirInfo.GetFiles()) { Console.WriteLine($"- {file.Name} ({file.Length} bytes)"); } Console.WriteLine("\nDirectories:"); foreach (DirectoryInfo dir in dirInfo.GetDirectories()) { Console.WriteLine($"- {dir.Name}"); } } }
GetFiles returns an array of FileInfo objects for the files in the directory. GetDirectories returns an array of DirectoryInfo objects for subdirectories. The example first creates a DirectoryInfo instance for the target directory.
It then uses GetFiles to retrieve all files and displays their names and sizes. GetDirectories retrieves all subdirectories, whose names are also displayed. These methods have overloads that accept search patterns and enumeration options for more control over the results.
Moving a Directory
DirectoryInfo allows moving directories to new locations. This example demonstrates how to move a directory using the MoveTo method.
using System; using System.IO; class Program { static void Main() { string sourcePath = @"C:\Temp\SourceDir"; string destPath = @"C:\Temp\DestDir"; DirectoryInfo sourceDir = new DirectoryInfo(sourcePath); if (!sourceDir.Exists) { sourceDir.Create(); Console.WriteLine($"Created source directory: {sourcePath}"); } if (Directory.Exists(destPath)) { Directory.Delete(destPath, true); Console.WriteLine($"Deleted existing destination: {destPath}"); } sourceDir.MoveTo(destPath); Console.WriteLine($"Moved directory from {sourcePath} to {destPath}"); } }
The MoveTo method moves a directory to a new location. The destination must not exist. The example first ensures the source directory exists by creating it if necessary. It then checks if the destination directory exists and deletes it if it does.
Finally, it moves the source directory to the destination path using MoveTo. Note that MoveTo can also be used to rename a directory by specifying a new name in the same parent directory. The operation is atomic at the file system level when moving within the same volume.
Searching for Files and Directories
DirectoryInfo provides search capabilities with patterns. This example shows how to search for specific files and directories using search patterns.
using System; using System.IO; class Program { static void Main() { DirectoryInfo dirInfo = new DirectoryInfo(@"C:\Temp"); Console.WriteLine("Text files:"); foreach (FileInfo file in dirInfo.GetFiles("*.txt")) { Console.WriteLine($"- {file.Name}"); } Console.WriteLine("\nDirectories starting with 'A':"); foreach (DirectoryInfo dir in dirInfo.GetDirectories("A*")) { Console.WriteLine($"- {dir.Name}"); } Console.WriteLine("\nAll PDF files (including subdirectories):"); foreach (FileInfo file in dirInfo.GetFiles("*.pdf", SearchOption.AllDirectories)) { Console.WriteLine($"- {file.FullName}"); } } }
GetFiles and GetDirectories accept search patterns like "*.txt" or "A*". SearchOption.AllDirectories enables recursive searching. The example demonstrates three different searches. First, it finds all .txt files in the directory using the "*.txt" pattern.
Second, it finds directories starting with 'A' using the "A*" pattern. Finally, it searches recursively for all PDF files in the directory and its subdirectories using SearchOption.AllDirectories. These search capabilities make it easy to find specific files or directories in complex directory structures.
Working with Directory Security
DirectoryInfo provides access to directory security information. This example shows how to get and set directory access control settings.
using System; using System.IO; using System.Security.AccessControl; class Program { static void Main() { string path = @"C:\Temp\SecureDir"; DirectoryInfo dirInfo = new DirectoryInfo(path); if (!dirInfo.Exists) { dirInfo.Create(); } // Get current security settings DirectorySecurity dirSecurity = dirInfo.GetAccessControl(); Console.WriteLine("Current access rules:"); foreach (FileSystemAccessRule rule in dirSecurity.GetAccessRules( true, true, typeof(System.Security.Principal.NTAccount))) { Console.WriteLine($"- {rule.IdentityReference}: {rule.FileSystemRights}"); } // Add a new rule dirSecurity.AddAccessRule(new FileSystemAccessRule( @"BUILTIN\Users", FileSystemRights.ReadAndExecute, AccessControlType.Allow)); dirInfo.SetAccessControl(dirSecurity); Console.WriteLine("\nAdded read/execute access for Users group."); } }
GetAccessControl retrieves the directory's security descriptor. SetAccessControl applies new security settings. The example first creates a directory if it doesn't exist. It then retrieves the current access control list using GetAccessControl.
The current rules are displayed using GetAccessRules. A new access rule is added to grant read and execute permissions to the Users group. Finally, the modified security descriptor is applied using SetAccessControl. This demonstrates how to programmatically manage directory permissions in C#.
Source
DirectoryInfo Class Documentation
This tutorial covered working with directories in C# using DirectoryInfo, including creation, deletion, enumeration, moving, and security management.
Author
List all C# tutorials.