System.IO.Directory Class

Overview

The System.IO.Directory class provides static methods for creating, moving, and enumerating through directories and subdirectories. It also offers functionality to retrieve information about the file system directories.

Key Methods

CreateDirectory

Creates all directories and subdirectories in the specified path.

Delete

Deletes an empty directory or a directory with its contents.

EnumerateFiles

Returns an enumerable collection of file names in a directory.

GetFiles

Gets the names of files (including their paths) in the specified directory.

GetDirectories

Retrieves the names of subdirectories (including their paths) in the specified directory.

Exists

Determines whether the given path refers to an existing directory.

Move

Moves a directory and its contents to a new location.

GetCurrentDirectory

Gets the current working directory of the application.

SetCurrentDirectory

Sets the application's current working directory.

Usage Example

The following C# example demonstrates how to create a directory, list its files, and delete it safely.

using System;
using System.IO;

class DirectoryDemo
{
    static void Main()
    {
        string path = @"C:\Temp\DemoFolder";

        // Create directory if it does not exist
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
            Console.WriteLine($"Created: {path}");
        }

        // Create a sample file inside the directory
        string filePath = Path.Combine(path, "sample.txt");
        File.WriteAllText(filePath, "Hello, Directory!");

        // List files in the directory
        Console.WriteLine("Files in directory:");
        foreach (var file in Directory.GetFiles(path))
        {
            Console.WriteLine($" - {Path.GetFileName(file)}");
        }

        // Clean up
        File.Delete(filePath);
        Directory.Delete(path);
        Console.WriteLine("Cleaned up.");
    }
}

Related Types