ZetCode

C# Directory

last modified April 20, 2025

This tutorial explains how to use the Directory class in C# to perform directory operations. Directory provides static methods for creating, moving, and enumerating through directories and subdirectories.

The Directory class exposes static methods for directory operations. It works with the DirectoryInfo class which provides instance methods.

Directory is useful for creating, deleting, moving directories and enumerating their contents. It handles path operations and directory permissions.

Checking Directory Existence

This example demonstrates how to check if a directory exists using the Directory.Exists method. This is often the first step in directory operations.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\Temp\TestDirectory";
        
        if (Directory.Exists(path))
        {
            Console.WriteLine("Directory exists.");
        }
        else
        {
            Console.WriteLine("Directory does not exist.");
        }
    }
}

The Directory.Exists method returns true if the specified path refers to an existing directory. The path can be relative or absolute. In this example, we check for the existence of a directory at "C:\Temp\TestDirectory".

The method performs a simple boolean check without throwing exceptions for invalid paths. This makes it safe to use before attempting other directory operations. Always verify directory existence before performing operations that might fail.

Creating a Directory

This example shows how to create a new directory using Directory.CreateDirectory. The method creates all directories and subdirectories in the specified path.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\Temp\NewDirectory";
        
        try
        {
            Directory.CreateDirectory(path);
            Console.WriteLine("Directory created successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

CreateDirectory creates all directories in the specified path that don't already exist. If the directory exists, the method does nothing. The example includes basic error handling for cases where creation might fail.

The method returns a DirectoryInfo object representing the created directory. We don't use the return value here but it's available for further operations. The path can contain multiple levels that don't yet exist.

Getting Directory Files

This example demonstrates how to get all files in a directory using Directory.GetFiles. The method returns an array of full paths.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\Temp";
        
        try
        {
            string[] files = Directory.GetFiles(path);
            
            Console.WriteLine("Files in directory:");
            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

GetFiles returns the names of all files in the specified directory. By default, it doesn't search subdirectories. The method has overloads for search patterns and search options.

The returned paths include the full directory path. The example shows basic error handling for cases where the directory might not be accessible. This is useful for directory listing operations.

Getting Subdirectories

This example shows how to get all subdirectories of a directory using Directory.GetDirectories. The method returns an array of paths.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\Temp";
        
        try
        {
            string[] dirs = Directory.GetDirectories(path);
            
            Console.WriteLine("Subdirectories:");
            foreach (string dir in dirs)
            {
                Console.WriteLine(dir);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

GetDirectories returns the names of all subdirectories in the specified directory. Like GetFiles, it has overloads for search patterns and options. The method doesn't recurse into subdirectories by default.

The returned paths are fully qualified. This example demonstrates basic directory traversal. Error handling ensures the program doesn't crash if the directory is inaccessible.

Moving a Directory

This example demonstrates how to move a directory using Directory.Move. The method moves a directory and its contents.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string sourceDir = @"C:\Temp\OldDir";
        string destDir = @"C:\Temp\NewDir";
        
        try
        {
            Directory.Move(sourceDir, destDir);
            Console.WriteLine("Directory moved successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Move transfers a directory to a new location. The destination must not exist. The operation is atomic on the same drive. Across drives, it's a copy-and-delete operation.

The method moves all contents including subdirectories. The example shows basic error handling for cases where the move might fail. This is useful for directory reorganization.

Deleting a Directory

This example shows how to delete a directory using Directory.Delete. The method can delete recursively.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\Temp\DirectoryToDelete";
        
        try
        {
            Directory.Delete(path, recursive: true);
            Console.WriteLine("Directory deleted successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Delete removes the specified directory. The recursive parameter determines whether to delete subdirectories and files. Without it, the directory must be empty.

The example shows deletion with recursive option enabled. Error handling catches cases where deletion might fail. This is useful for cleanup operations.

Getting Directory Information

This example demonstrates how to get directory creation, access, and write times using Directory class methods.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\Temp";
        
        try
        {
            Console.WriteLine($"Creation time: {Directory.GetCreationTime(path)}");
            Console.WriteLine($"Last access time: {Directory.GetLastAccessTime(path)}");
            Console.WriteLine($"Last write time: {Directory.GetLastWriteTime(path)}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

The Directory class provides methods to get various timestamps. These include creation time, last access time, and last write time. The times are returned as DateTime values.

The example shows basic directory metadata retrieval. Error handling ensures the program doesn't crash if the directory is inaccessible. This is useful for directory monitoring and logging.

Source

Directory Class Documentation

This tutorial covered directory operations in C# with the Directory class, including creation, deletion, moving, and enumeration of directories.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all C# tutorials.