How to use the directory class in C#?

The Directory class in C# is used to manipulate the directory structure. It provides static methods to create, move, delete, and query directories without needing to create an instance of the class.

The Directory class is part of the System.IO namespace and offers essential functionality for working with file system directories programmatically.

Syntax

Following is the basic syntax for using Directory class methods −

Directory.MethodName(path);
Directory.MethodName(path, parameters);

Common Directory Class Methods

Method Description
CreateDirectory(String) Creates all directories and subdirectories in the specified path
Delete(String) Deletes an empty directory from the specified path
Exists(String) Determines whether the given path refers to an existing directory
GetFiles(String) Returns the names of files in the specified directory
GetDirectories(String) Returns the names of subdirectories in the specified directory
GetCurrentDirectory() Gets the current working directory of the application

Directory Class Operations Create Query Delete CreateDirectory() Creates new directories Exists() GetFiles() GetDirectories() Check & list Delete() Removes empty directories

Using Directory.CreateDirectory()

Example

using System;
using System.IO;

class Program {
    static void Main() {
        string dirPath = @"C:\TestDirectory\SubDirectory";
        
        if (!Directory.Exists(dirPath)) {
            Directory.CreateDirectory(dirPath);
            Console.WriteLine("Directory created successfully: " + dirPath);
        } else {
            Console.WriteLine("Directory already exists: " + dirPath);
        }
        
        Console.WriteLine("Current Directory: " + Directory.GetCurrentDirectory());
    }
}

The output of the above code is −

Directory created successfully: C:\TestDirectory\SubDirectory
Current Directory: C:\Users\YourUsername\source\repos\ProjectName\bin\Debug

Using Directory.GetFiles()

Example

using System;
using System.IO;

class Program {
    static void Main() {
        // First create a test directory with some files
        string testDir = @"C:\TestFiles";
        Directory.CreateDirectory(testDir);
        
        // Create some test files
        File.WriteAllText(Path.Combine(testDir, "file1.txt"), "Sample content");
        File.WriteAllText(Path.Combine(testDir, "file2.txt"), "Another file");
        File.WriteAllText(Path.Combine(testDir, "document.doc"), "Document content");
        
        // Get all files in the directory
        string[] files = Directory.GetFiles(testDir);
        
        Console.WriteLine("Files in " + testDir + ":");
        foreach (string file in files) {
            Console.WriteLine(Path.GetFileName(file));
        }
        
        // Get only .txt files
        string[] txtFiles = Directory.GetFiles(testDir, "*.txt");
        Console.WriteLine("\nOnly .txt files:");
        foreach (string txtFile in txtFiles) {
            Console.WriteLine(Path.GetFileName(txtFile));
        }
    }
}

The output of the above code is −

Files in C:\TestFiles:
document.doc
file1.txt
file2.txt

Only .txt files:
file1.txt
file2.txt

Using Directory.GetDirectories()

Example

using System;
using System.IO;

class Program {
    static void Main() {
        // Create test directories
        string baseDir = @"C:\TestBase";
        Directory.CreateDirectory(Path.Combine(baseDir, "Folder1"));
        Directory.CreateDirectory(Path.Combine(baseDir, "Folder2"));
        Directory.CreateDirectory(Path.Combine(baseDir, "Documents"));
        
        // Get all subdirectories
        string[] directories = Directory.GetDirectories(baseDir);
        
        Console.WriteLine("Subdirectories in " + baseDir + ":");
        foreach (string dir in directories) {
            Console.WriteLine(Path.GetFileName(dir));
        }
        
        // Check if directory exists before deletion
        string dirToDelete = Path.Combine(baseDir, "Folder1");
        if (Directory.Exists(dirToDelete)) {
            Directory.Delete(dirToDelete);
            Console.WriteLine("\nDeleted: " + Path.GetFileName(dirToDelete));
        }
    }
}

The output of the above code is −

Subdirectories in C:\TestBase:
Documents
Folder1
Folder2

Deleted: Folder1

Key Points

  • Always use Directory.Exists() before creating or deleting directories to avoid exceptions.

  • Use the @ symbol before string literals to avoid escaping backslashes in path names.

  • Directory.Delete() only works on empty directories. Use Directory.Delete(path, true) to delete directories recursively.

  • The Path.Combine() method is recommended for building file paths safely across different operating systems.

Conclusion

The Directory class in C# provides essential static methods for directory manipulation including creation, deletion, existence checking, and content listing. It is a fundamental tool for file system operations in .NET applications, offering both basic and advanced directory management capabilities.

Updated on: 2026-03-17T07:04:35+05:30

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements