C# Reference ยท Files and I/O
The Directory class
Reference for System.IO.Directory in C#: create, list, search, move and delete directories, EnumerationOptions, recursion, temp folders, and common exceptions.
System.IO.Directory is a static class for folders. You use it to create a directory, check whether one exists, list the files and subfolders inside, move or rename a directory, and delete it. Like File, its methods take path strings, so no object is needed. The object-based version is DirectoryInfo (see FileInfo and DirectoryInfo).
The listing methods come in two flavors. GetFiles and GetDirectories build an array and return when the scan is complete. EnumerateFiles and EnumerateDirectories return a lazy sequence, which starts producing results immediately and uses far less memory in large trees.
Directory.CreateDirectory("output/reports"); foreach (string file in Directory.EnumerateFiles("output", "*.txt", SearchOption.AllDirectories)) { Console.WriteLine(file); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static DirectoryInfo CreateDirectory(string path); public static DirectoryInfo CreateTempSubdirectory(string? prefix = null); public static bool Exists(string? path); public static void Delete(string path, bool recursive); public static void Move(string sourceDirName, string destDirName); public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption); public static string[] GetFiles(string path, string searchPattern, EnumerationOptions options); public static string[] GetDirectories(string path); public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption); public static IEnumerable<string> EnumerateFileSystemEntries(string path); public static string GetCurrentDirectory(); public static DirectoryInfo? GetParent(string path);
| Parameter | Description |
|---|---|
path |
Directory to create, test, list or delete. |
searchPattern |
A pattern with * (any characters) and ? (one character). Default is *. No regular expressions. |
searchOption |
TopDirectoryOnly (default) or AllDirectories. |
options |
An EnumerationOptions object: RecurseSubdirectories, IgnoreInaccessible (default true), MatchCasing, AttributesToSkip, MaxRecursionDepth, ReturnSpecialDirectories. |
recursive |
true also deletes the contents. |
Returns: CreateDirectory returns a DirectoryInfo (also when the folder already existed). Get... methods return full paths, in the form you gave: a relative path gives relative results.
Errors: DirectoryNotFoundException (path missing), IOException (directory not empty, target exists, path is a file), UnauthorizedAccessException (no permission), ArgumentException (empty or invalid path).
Usage notes
CreateDirectoryis idempotent. It does nothing if the folder exists and creates all missing parents, so you can call it withoutExists.- Order is not guaranteed. Listing methods return entries in file-system order, which differs between operating systems. Sort them (
Order()) when the output matters. GetversusEnumerate. UseEnumerate...in a loop and for early exit withTake/FirstOrDefault; useGet...when you need an array or a count and the folder is small. Do not modify the folder tree while enumerating it.- Case sensitivity of patterns follows the platform by default: case-insensitive on Windows and macOS, case-sensitive on Linux. Set
MatchCasingexplicitly for portable code. - Inaccessible folders.
EnumerationOptions.IgnoreInaccessibleistrueby default, so unreadable subfolders are skipped silently, while the olderSearchOptionoverloads throwUnauthorizedAccessException. Check which overload you use when you scan large trees. - Recursive delete is permanent.
Delete(path, true)bypasses the recycle bin. Double-check the path before calling it. - Move across volumes.
Directory.Moveworks within one volume on most systems; across volumes, copy the tree and delete the old one. - Temp folders.
Directory.CreateTempSubdirectory(.NET 7+) creates a uniquely named folder underPath.GetTempPath(). Delete it when you finish. On the runner of this site the temp area is a throwaway sandbox. - Current directory.
Directory.SetCurrentDirectorychanges the base for relative paths for the whole process, including other threads. Avoid it in libraries.