ZetCode

C# Directory

last modified November 6, 2026

In this article we show how to work with directories in C# using the Directory class.

The Directory class from the System.IO namespace provides static methods for creating, moving, deleting, and enumerating directories. Its counterpart, the DirectoryInfo class, offers the same operations as instance methods and properties of an object that represents one directory.

The methods accept relative and absolute paths. Relative paths are resolved against the current working directory. To build paths that work on Windows, Linux, and macOS, we combine their parts with Path.Combine instead of hard-coding separators. The examples create a small demo directory in the working directory and delete it at the end; the outputs come from Linux.

Checking and creating directories

Directory.Exists checks whether a directory exists, and Directory.CreateDirectory creates it.

Program.cs
string path = Path.Combine("demo", "reports", "2026");

Console.WriteLine($"exists: {Directory.Exists(path)}");

DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine($"created: {di.Name}, parent: {di.Parent?.Name}");
Console.WriteLine($"exists: {Directory.Exists(path)}");

Directory.CreateDirectory(path);
Console.WriteLine("second call did not throw");

File.WriteAllText(Path.Combine("demo", "notes.txt"), "text");
Console.WriteLine($"file is a directory: {Directory.Exists(Path.Combine("demo", "notes.txt"))}");

Directory.Delete("demo", recursive: true);

We create a nested directory and check its existence before and after.

DirectoryInfo di = Directory.CreateDirectory(path);

CreateDirectory creates all missing directories in the path, here demo, demo/reports, and demo/reports/2026. It returns a DirectoryInfo object for the last one.

Directory.CreateDirectory(path);
Console.WriteLine("second call did not throw");

If the directory already exists, the method does nothing. There is no need to call Exists before it.

Console.WriteLine($"file is a directory: {Directory.Exists(Path.Combine("demo", "notes.txt"))}");

Exists returns false for a file, and also for invalid paths or directories the program has no permission to access; it never throws.

Directory.Delete("demo", recursive: true);

At the end we delete the directory with all its contents.

$ dotnet run
exists: False
created: 2026, parent: reports
exists: True
second call did not throw
file is a directory: False

Listing files and subdirectories

GetFiles and GetDirectories return arrays with the paths of the files and subdirectories. Optional parameters filter the names with a search pattern and include subdirectories.

Program.cs
CreateSample("demo");

string[] files = Directory.GetFiles("demo");
Array.Sort(files);

Console.WriteLine("files in demo:");
foreach (string file in files)
{
    Console.WriteLine($"  {file}");
}

Console.WriteLine("text files in all subdirectories:");
foreach (string file in Directory.GetFiles("demo", "*.txt", SearchOption.AllDirectories).Order())
{
    Console.WriteLine($"  {Path.GetRelativePath("demo", file)}");
}

Console.WriteLine("subdirectories:");
foreach (string dir in Directory.GetDirectories("demo").Order())
{
    Console.WriteLine($"  {Path.GetFileName(dir)}");
}

Directory.Delete("demo", recursive: true);

static void CreateSample(string root)
{
    Directory.CreateDirectory(Path.Combine(root, "docs", "old"));
    Directory.CreateDirectory(Path.Combine(root, "images"));

    string[] names = ["readme.txt", "data.csv", "docs/guide.txt", "docs/old/draft.txt",
        "images/logo.png", "images/photo.jpg"];

    foreach (string name in names)
    {
        File.WriteAllText(Path.Combine(root, name), name);
    }
}

We create a sample tree and list its files, the text files in all subdirectories, and its subdirectories.

string[] files = Directory.GetFiles("demo");
Array.Sort(files);

The returned paths start with the path we passed in. The order of the entries is not guaranteed and differs between file systems, so we sort them.

foreach (string file in Directory.GetFiles("demo", "*.txt", SearchOption.AllDirectories).Order())

The *.txt pattern matches names ending in .txt; the * wildcard matches any characters and ? a single character. SearchOption.AllDirectories searches the whole tree.

Console.WriteLine($"  {Path.GetRelativePath("demo", file)}");

Path.GetRelativePath shortens the paths, and Path.GetFileName returns the last part of a path.

$ dotnet run
files in demo:
  demo/data.csv
  demo/readme.txt
text files in all subdirectories:
  docs/guide.txt
  docs/old/draft.txt
  readme.txt
subdirectories:
  docs
  images

Enumerating lazily

The Enumerate* methods return an IEnumerable<string> that yields the entries while the directory is being read. They are more efficient than the Get* methods for large directories, because the processing can start immediately and stop early.

Program.cs
CreateSample("demo");

long total = 0;
int count = 0;

foreach (string file in Directory.EnumerateFiles("demo", "*", SearchOption.AllDirectories))
{
    total += new FileInfo(file).Length;
    count++;
}

Console.WriteLine($"{count} files, {total} bytes");

string? firstImage = Directory.EnumerateFiles("demo", "*.png", SearchOption.AllDirectories)
    .FirstOrDefault();
Console.WriteLine($"first png: {Path.GetFileName(firstImage)}");

var entries = Directory.EnumerateFileSystemEntries("demo")
    .Select(Path.GetFileName)
    .Order();
Console.WriteLine($"entries: {string.Join(", ", entries)}");

Directory.Delete("demo", recursive: true);

static void CreateSample(string root)
{
    Directory.CreateDirectory(Path.Combine(root, "docs"));
    Directory.CreateDirectory(Path.Combine(root, "images"));

    File.WriteAllText(Path.Combine(root, "readme.txt"), "read me");
    File.WriteAllText(Path.Combine(root, "docs", "guide.txt"), "a short guide");
    File.WriteAllBytes(Path.Combine(root, "images", "logo.png"), new byte[2048]);
}

We compute the total size of all files, find the first PNG image, and list all entries of the top directory.

string? firstImage = Directory.EnumerateFiles("demo", "*.png", SearchOption.AllDirectories)
    .FirstOrDefault();

FirstOrDefault stops the enumeration as soon as the first image is found; the rest of the tree is not visited.

var entries = Directory.EnumerateFileSystemEntries("demo")

EnumerateFileSystemEntries returns both files and directories.

$ dotnet run
3 files, 2068 bytes
first png: logo.png
entries: docs, images, readme.txt

EnumerationOptions

The EnumerationOptions class gives finer control over the search: recursion depth, case sensitivity, skipped attributes, and the handling of inaccessible directories.

Program.cs
Directory.CreateDirectory(Path.Combine("demo", "sub", ".cache"));
Directory.CreateDirectory(Path.Combine("demo", "sub", "deep", "deeper"));

string[] names = ["a.txt", "B.TXT", ".hidden.txt", "sub/c.txt", "sub/.cache/d.txt",
    "sub/deep/e.txt", "sub/deep/deeper/f.txt"];

foreach (string name in names)
{
    File.WriteAllText(Path.Combine("demo", name), "");
}

var options = new EnumerationOptions
{
    RecurseSubdirectories = true,
    MaxRecursionDepth = 2,
    MatchCasing = MatchCasing.CaseInsensitive,
    IgnoreInaccessible = true,
};

Print("default", Directory.GetFiles("demo", "*.txt", SearchOption.AllDirectories));
Print("options", Directory.GetFiles("demo", "*.txt", options));

options.AttributesToSkip = 0;
Print("with hidden", Directory.GetFiles("demo", "*.txt", options));

Directory.Delete("demo", recursive: true);

static void Print(string label, string[] files)
{
    var names = files.Select(f => Path.GetRelativePath("demo", f)).Order();
    Console.WriteLine($"{label}: {string.Join(" ", names)}");
}

We search a tree with hidden files, upper-case extensions, and several levels of subdirectories, first with the default behavior and then with options.

var options = new EnumerationOptions
{
    RecurseSubdirectories = true,
    MaxRecursionDepth = 2,
    MatchCasing = MatchCasing.CaseInsensitive,
    IgnoreInaccessible = true,
};

The search goes at most two levels deep, matches names regardless of case, and skips directories it cannot read instead of throwing UnauthorizedAccessException.

With the default behavior, the pattern is case-sensitive on Linux, so B.TXT is missing, and hidden files are included. A new EnumerationOptions object skips hidden and system entries; on Unix, names starting with a dot are hidden. Setting AttributesToSkip to 0 includes them again.

$ dotnet run
default: .hidden.txt a.txt sub/.cache/d.txt sub/c.txt sub/deep/deeper/f.txt sub/deep/e.txt
options: a.txt B.TXT sub/c.txt sub/deep/e.txt
with hidden: .hidden.txt a.txt B.TXT sub/.cache/d.txt sub/c.txt sub/deep/e.txt

Moving and deleting directories

Directory.Move moves or renames a directory with all its contents, and Directory.Delete removes it.

Program.cs
Directory.CreateDirectory(Path.Combine("demo", "old", "sub"));
File.WriteAllText(Path.Combine("demo", "old", "sub", "data.txt"), "data");

Directory.Move(Path.Combine("demo", "old"), Path.Combine("demo", "archive"));

Console.WriteLine($"old exists: {Directory.Exists(Path.Combine("demo", "old"))}");
Console.WriteLine($"moved file exists: {File.Exists(Path.Combine("demo", "archive", "sub", "data.txt"))}");

try
{
    Directory.Delete(Path.Combine("demo", "archive"));
}
catch (IOException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message.Replace(Environment.CurrentDirectory, ".")}");
}

Directory.Delete(Path.Combine("demo", "archive"), recursive: true);
Console.WriteLine($"archive exists: {Directory.Exists(Path.Combine("demo", "archive"))}");

Directory.Delete("demo");

We rename a directory, try to delete it while it is not empty, and then delete it recursively.

Directory.Move(Path.Combine("demo", "old"), Path.Combine("demo", "archive"));

The destination must not exist. Moving to another drive or volume is not supported and throws an IOException.

Directory.Delete(Path.Combine("demo", "archive"));

Without the recursive argument, only an empty directory can be deleted.

Directory.Delete(Path.Combine("demo", "archive"), recursive: true);

The recursive delete removes the directory with all files and subdirectories. It is permanent; the files do not go to the recycle bin.

$ dotnet run
old exists: False
moved file exists: True
IOException: Directory not empty : './demo/archive'
archive exists: False

Copying a directory

The Directory class has no method for copying a directory. We write a recursive function.

Program.cs
Directory.CreateDirectory(Path.Combine("demo", "src", "lib"));
File.WriteAllText(Path.Combine("demo", "src", "main.cs"), "main");
File.WriteAllText(Path.Combine("demo", "src", "lib", "util.cs"), "util");

CopyDirectory(Path.Combine("demo", "src"), Path.Combine("demo", "backup"));

foreach (string f in Directory.GetFiles("demo", "*", SearchOption.AllDirectories).Order())
{
    Console.WriteLine(f);
}

Directory.Delete("demo", recursive: true);

static void CopyDirectory(string source, string target)
{
    Directory.CreateDirectory(target);

    foreach (string file in Directory.GetFiles(source))
    {
        File.Copy(file, Path.Combine(target, Path.GetFileName(file)), overwrite: true);
    }

    foreach (string dir in Directory.GetDirectories(source))
    {
        CopyDirectory(dir, Path.Combine(target, Path.GetFileName(dir)));
    }
}

We copy a source tree into a backup directory.

foreach (string file in Directory.GetFiles(source))
{
    File.Copy(file, Path.Combine(target, Path.GetFileName(file)), overwrite: true);
}

The files of the current directory are copied to the target.

foreach (string dir in Directory.GetDirectories(source))
{
    CopyDirectory(dir, Path.Combine(target, Path.GetFileName(dir)));
}

The function calls itself for each subdirectory.

$ dotnet run
demo/backup/lib/util.cs
demo/backup/main.cs
demo/src/lib/util.cs
demo/src/main.cs

Directory timestamps

The Directory class reads and sets the creation, last access, and last write times of a directory.

Program.cs
Directory.CreateDirectory("demo");

var created = Directory.GetCreationTime("demo");
Console.WriteLine($"created today: {created.Date == DateTime.Today}");

var stamp = new DateTime(2025, 12, 24, 18, 0, 0);
Directory.SetLastWriteTime("demo", stamp);
Directory.SetLastAccessTime("demo", stamp.AddDays(1));

Console.WriteLine($"last write:  {Directory.GetLastWriteTime("demo"):yyyy-MM-dd HH:mm}");
Console.WriteLine($"last access: {Directory.GetLastAccessTime("demo"):yyyy-MM-dd HH:mm}");

File.WriteAllText(Path.Combine("demo", "new.txt"), "");
Console.WriteLine($"write time updated: {Directory.GetLastWriteTime("demo") > stamp}");

Console.WriteLine($"missing: {Directory.GetLastWriteTime("missing"):yyyy-MM-dd}");

Directory.Delete("demo", recursive: true);

We set the timestamps of a directory and see how they change.

Directory.SetLastWriteTime("demo", stamp);

Setting the time is useful when restoring backups or extracting archives.

File.WriteAllText(Path.Combine("demo", "new.txt"), "");

Creating a file in the directory updates the directory's last write time.

Console.WriteLine($"missing: {Directory.GetLastWriteTime("missing"):yyyy-MM-dd}");

For a directory that does not exist, the methods return January 1, 1601, adjusted to local time, instead of throwing an exception.

$ dotnet run
created today: True
last write:  2025-12-24 18:00
last access: 2025-12-25 18:00
write time updated: True
missing: 1601-01-01

Special directories

Several methods return information about the working directory, the root, and temporary and user directories.

Program.cs
string cwd = Directory.GetCurrentDirectory();
Console.WriteLine($"current directory is absolute: {Path.IsPathRooted(cwd)}");

string root = Directory.GetDirectoryRoot(cwd);
Console.WriteLine($"root: {root}");

DirectoryInfo? parent = Directory.GetParent(Path.Combine("projects", "app", "src"));
Console.WriteLine($"parent: {parent?.Name}");

DirectoryInfo temp = Directory.CreateTempSubdirectory("demo-");
Console.WriteLine($"temp dir: {temp.FullName}");
temp.Delete();

string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
Console.WriteLine($"home exists: {Directory.Exists(home)}");

Console.WriteLine($"logical drives: {string.Join(" ", Directory.GetLogicalDrives().Take(3))}");

We query the current directory and its root, the parent of a path, a temporary directory, and the home directory.

DirectoryInfo? parent = Directory.GetParent(Path.Combine("projects", "app", "src"));

GetParent works with the path; the directories need not exist.

DirectoryInfo temp = Directory.CreateTempSubdirectory("demo-");

CreateTempSubdirectory, available since .NET 7, creates a uniquely named directory in the system's temporary directory.

string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

Environment.GetFolderPath returns well-known directories such as the home or documents directory.

Console.WriteLine($"logical drives: {string.Join(" ", Directory.GetLogicalDrives().Take(3))}");

On Windows, GetLogicalDrives returns drive letters such as C:\. On Linux, it returns the mount points.

$ dotnet run
current directory is absolute: True
root: /
parent: app
temp dir: /tmp/demo-OvBZlI
home exists: True
logical drives: /sys /proc /dev

Source

Directory class

In this article we have worked with directories in C# using the Directory class.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.