ZetCode

C# Directory

last modified November 6, 2026

In this article we show how to work with directories in C#. We create, delete, move, list, and copy directories.

A directory, also called a folder, is a location for storing files in a file system. A directory can contain files and other directories, called subdirectories.

.NET provides two classes for working with directories in the System.IO namespace:

Directory is convenient for one-off operations; DirectoryInfo is better when we work with the same directory repeatedly. The examples in this article run on Windows, Linux, and macOS. Each example creates a demo directory in the current working directory and deletes it at the end. The Directory class, DirectoryInfo class, and list directory articles cover these classes in more depth.

Create a directory

The Directory.CreateDirectory method creates a directory, including all missing parent directories.

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

DirectoryInfo di = Directory.CreateDirectory(path);

Console.WriteLine($"Name: {di.Name}");
Console.WriteLine($"Parent: {di.Parent?.Name}");
Console.WriteLine($"Exists: {Directory.Exists(path)}");

DirectoryInfo again = Directory.CreateDirectory(path);
Console.WriteLine($"Second call: {again.Name}, no error");

Directory.Delete("demo", recursive: true);
Console.WriteLine($"Exists after delete: {Directory.Exists(path)}");

Path.Combine joins the path parts with the separator of the current operating system.

DirectoryInfo di = Directory.CreateDirectory(path);

The method creates demo, demo/data, and demo/data/2026, and returns a DirectoryInfo for the last one.

DirectoryInfo again = Directory.CreateDirectory(path);

If the directory already exists, CreateDirectory does nothing and does not throw. We do not need to check with Exists first.

$ dotnet run
Name: 2026
Parent: data
Exists: True
Second call: 2026, no error
Exists after delete: False

Current directory

Relative paths are resolved against the current working directory of the process.

Program.cs
string start = Directory.GetCurrentDirectory();
Console.WriteLine($"Root: {Directory.GetDirectoryRoot(start)}");

Directory.CreateDirectory("demo");
Directory.SetCurrentDirectory("demo");

Console.WriteLine($"Now in: {Path.GetFileName(Directory.GetCurrentDirectory())}");
Console.WriteLine($"Relative path resolves to: {Path.GetRelativePath(start, Path.GetFullPath("notes.txt"))}");

Directory.SetCurrentDirectory(start);
Directory.Delete("demo");
Console.WriteLine($"Back in start directory: {Directory.GetCurrentDirectory() == start}");

GetCurrentDirectory returns the working directory, and GetDirectoryRoot its root; / on Unix systems and a drive such as C:\ on Windows.

Directory.SetCurrentDirectory("demo");

SetCurrentDirectory changes the working directory for the whole process. Relative paths, such as notes.txt, now resolve inside demo.

Directory.SetCurrentDirectory(start);
Directory.Delete("demo");

We return to the original directory before deleting demo.

$ dotnet run
Root: /
Now in: demo
Relative path resolves to: demo/notes.txt
Back in start directory: True

Delete a directory

The Directory.Delete method removes a directory.

Program.cs
Directory.CreateDirectory("demo/sub");
File.WriteAllText("demo/sub/notes.txt", "some notes");

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

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

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

By default, Delete removes only empty directories. For a directory with content, it throws an IOException.

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

With recursive set to true, the method deletes the directory with all its files and subdirectories. Use it with care; deleted items do not go to the recycle bin.

catch (DirectoryNotFoundException e)

Deleting a directory that does not exist throws DirectoryNotFoundException.

$ dotnet run
IOException: Directory not empty : './demo'
Exists: False
DirectoryNotFoundException: Could not find a part of the path './demo'.

Move and rename a directory

The Directory.Move method moves a directory with its content to a new location. Renaming is a move within the same parent.

Program.cs
Directory.CreateDirectory("demo/drafts");
Directory.CreateDirectory("demo/archive");
File.WriteAllText("demo/drafts/report.txt", "Q3 report");

Directory.Move("demo/drafts", "demo/final");
Console.WriteLine($"drafts exists: {Directory.Exists("demo/drafts")}");
Console.WriteLine($"final exists: {Directory.Exists("demo/final")}");

Directory.Move("demo/final", "demo/archive/2026");
Console.WriteLine(File.ReadAllText("demo/archive/2026/report.txt"));

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

Directory.Delete("demo", true);

The first call renames drafts to final.

Directory.Move("demo/final", "demo/archive/2026");

The second call moves the directory into archive under a new name. The destination must not exist yet.

Directory.Move("demo/archive", "demo/archive/old");

A directory cannot be moved into itself. The exception message comes from the operating system; on Linux, it is Invalid argument.

$ dotnet run
drafts exists: False
final exists: True
Q3 report
IOException: Invalid argument

List directories and files

GetDirectories, GetFiles, and GetFileSystemEntries return the paths of subdirectories, files, or both.

Program.cs
CreateTree();

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

Console.WriteLine("Directories starting with 'w':");
foreach (string dir in Directory.GetDirectories("demo", "w*").Order())
{
    Console.WriteLine($"  {dir}");
}

Console.WriteLine("Text files:");
foreach (string file in Directory.GetFiles("demo", "*.txt").Order())
{
    Console.WriteLine($"  {Path.GetFileName(file)}");
}

Console.WriteLine("All entries:");
foreach (string entry in Directory.GetFileSystemEntries("demo").Order())
{
    string kind = Directory.Exists(entry) ? "dir " : "file";
    Console.WriteLine($"  {kind} {Path.GetFileName(entry)}");
}

Directory.Delete("demo", true);

static void CreateTree()
{
    foreach (string d in new[] { "web", "work", "music" })
    {
        Directory.CreateDirectory(Path.Combine("demo", d));
    }

    File.WriteAllText("demo/todo.txt", "buy milk");
    File.WriteAllText("demo/words.txt", "sky blue");
    File.WriteAllText("demo/data.csv", "1,2,3");
}

The returned order depends on the file system, so we sort the paths with Order.

foreach (string dir in Directory.GetDirectories("demo", "w*").Order())

The second parameter is a search pattern. The * wildcard matches zero or more characters and ? matches exactly one.

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

The returned paths include the directory we searched. We print only the file names with Path.GetFileName.

string kind = Directory.Exists(entry) ? "dir " : "file";

GetFileSystemEntries returns both kinds of entries. We use Directory.Exists to tell them apart.

$ dotnet run
Directories:
  demo/music
  demo/web
  demo/work
Directories starting with 'w':
  demo/web
  demo/work
Text files:
  todo.txt
  words.txt
All entries:
  file data.csv
  dir  music
  file todo.txt
  dir  web
  file words.txt
  dir  work

Search recursively

With SearchOption.AllDirectories, the methods search the whole directory tree.

Program.cs
Directory.CreateDirectory("demo/src/models");
Directory.CreateDirectory("demo/src/views");
Directory.CreateDirectory("demo/tests");
File.WriteAllText("demo/README.md", "# Demo");
File.WriteAllText("demo/src/Program.cs", "Console.WriteLine();");
File.WriteAllText("demo/src/models/User.cs", "record User(string Name);");
File.WriteAllText("demo/src/views/index.html", "<p>hello</p>");
File.WriteAllText("demo/tests/UserTests.cs", "// tests");

var csFiles = Directory.EnumerateFiles("demo", "*.cs", SearchOption.AllDirectories)
    .Select(f => Path.GetRelativePath("demo", f))
    .Order();

Console.WriteLine("C# files:");
foreach (string f in csFiles)
{
    Console.WriteLine($"  {f}");
}

long size = Directory.EnumerateFiles("demo", "*", SearchOption.AllDirectories)
    .Sum(f => new FileInfo(f).Length);

int dirs = Directory.EnumerateDirectories("demo", "*", SearchOption.AllDirectories).Count();

Console.WriteLine($"Subdirectories: {dirs}");
Console.WriteLine($"Total size: {size} bytes");

Directory.Delete("demo", true);

We create a small project tree with files in several subdirectories.

var csFiles = Directory.EnumerateFiles("demo", "*.cs", SearchOption.AllDirectories)
    .Select(f => Path.GetRelativePath("demo", f))
    .Order();

The Enumerate methods return a lazy sequence instead of an array, so they can start returning results before the whole tree is read. GetRelativePath shortens the paths.

long size = Directory.EnumerateFiles("demo", "*", SearchOption.AllDirectories)
    .Sum(f => new FileInfo(f).Length);

The size of a directory is the sum of the sizes of all files in its tree.

$ dotnet run
C# files:
  src/models/User.cs
  src/Program.cs
  tests/UserTests.cs
Subdirectories: 4
Total size: 71 bytes

Copy a directory

.NET has no method for copying a directory. We write a recursive function that copies the files and then the subdirectories.

Program.cs
Directory.CreateDirectory("demo/site/css");
Directory.CreateDirectory("demo/site/img/icons");
File.WriteAllText("demo/site/index.html", "<h1>Home</h1>");
File.WriteAllText("demo/site/css/main.css", "body { margin: 0 }");
File.WriteAllText("demo/site/img/icons/logo.svg", "<svg/>");

int copied = CopyDirectory("demo/site", "demo/backup");
Console.WriteLine($"Copied {copied} files");

foreach (string f in Directory.EnumerateFiles("demo/backup", "*", SearchOption.AllDirectories).Order())
{
    Console.WriteLine($"  {Path.GetRelativePath("demo", f)}");
}

Directory.Delete("demo", true);

static int CopyDirectory(string source, string dest)
{
    if (!Directory.Exists(source))
    {
        throw new DirectoryNotFoundException($"Source directory not found: {source}");
    }

    Directory.CreateDirectory(dest);
    int count = 0;

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

    foreach (string dir in Directory.GetDirectories(source))
    {
        count += CopyDirectory(dir, Path.Combine(dest, Path.GetFileName(dir)));
    }

    return count;
}

The function copies the files of the source directory, then calls itself for each subdirectory. It returns the number of copied files.

File.Copy(file, Path.Combine(dest, Path.GetFileName(file)), overwrite: true);

Each file is copied into the destination directory under the same name. Existing files are overwritten.

$ dotnet run
Copied 3 files
  backup/css/main.css
  backup/img/icons/logo.svg
  backup/index.html

Directory times

The Directory class can read and set the creation, last access, and last write times of a directory.

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

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

var date = new DateTime(2025, 12, 24, 18, 30, 0);
Directory.SetLastWriteTime("demo", date);
Directory.SetLastAccessTime("demo", date.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("demo/new.txt", "x");
Console.WriteLine($"Last write after adding a file: {Directory.GetLastWriteTime("demo").Date == DateTime.Today}");

Directory.Delete("demo", true);

GetCreationTime returns the creation time in local time. The GetCreationTimeUtc variant returns UTC.

Directory.SetLastWriteTime("demo", date);
Directory.SetLastAccessTime("demo", date.AddDays(1));

We set the times to a fixed date and read them back.

File.WriteAllText("demo/new.txt", "x");

Adding a file to a directory changes the directory's last write time.

$ dotnet run
Created today: True
Last write: 2025-12-24 18:30
Last access: 2025-12-25 18:30
Last write after adding a file: True

Temporary directory

The Directory.CreateTempSubdirectory method creates a directory with a unique name inside the system's temporary directory.

Program.cs
DirectoryInfo tmp = Directory.CreateTempSubdirectory("report-");

Console.WriteLine($"Name starts with prefix: {tmp.Name.StartsWith("report-")}");
Console.WriteLine($"Inside temp path: {tmp.Parent?.FullName == Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar)}");

try
{
    File.WriteAllText(Path.Combine(tmp.FullName, "part1.txt"), "first part");
    File.WriteAllText(Path.Combine(tmp.FullName, "part2.txt"), "second part");

    Console.WriteLine($"Files: {Directory.GetFiles(tmp.FullName).Length}");
}
finally
{
    tmp.Delete(recursive: true);
}

Console.WriteLine($"Exists: {Directory.Exists(tmp.FullName)}");

The optional argument is a prefix of the generated name.

finally
{
    tmp.Delete(recursive: true);
}

The system does not always delete temporary directories, so we remove it ourselves in a finally block.

$ dotnet run
Name starts with prefix: True
Inside temp path: True
Files: 2
Exists: False

Unix permissions

On Linux and macOS, CreateDirectory can set the permissions of the new directory with a UnixFileMode value.

Program.cs
if (OperatingSystem.IsWindows())
{
    Console.WriteLine("Unix file modes are not supported on Windows");
    return;
}

DirectoryInfo priv = Directory.CreateDirectory("demo-private",
    UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);

Show(priv);

File.SetUnixFileMode(priv.FullName, priv.UnixFileMode | UnixFileMode.GroupRead | UnixFileMode.GroupExecute);
priv.Refresh();
Show(priv);

priv.Delete();

static void Show(DirectoryInfo di)
{
    string octal = Convert.ToString((int)di.UnixFileMode, 8);
    Console.WriteLine($"{octal}: {di.UnixFileMode}");
}

The directory is created with mode 700: only the owner can read, write, and enter it. The mode is still restricted by the process's umask.

File.SetUnixFileMode(priv.FullName, priv.UnixFileMode | UnixFileMode.GroupRead | UnixFileMode.GroupExecute);
priv.Refresh();

File.SetUnixFileMode works for directories as well. The DirectoryInfo object caches its properties, so we call Refresh to read the new mode. On Windows, access is controlled by access control lists, which are managed with the DirectorySecurity class.

$ dotnet run
700: UserExecute, UserWrite, UserRead
750: GroupExecute, GroupRead, UserExecute, UserWrite, UserRead

Source

Directory class

In this article we have worked with directories in C#.

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.