Directory.Exists() / Directory.CreateDirectory()
| Since: | C# 1.0(2002) |
|---|
How to use the Directory class to check for existence, create, delete, and list files in directories.
Syntax
using System.IO; bool exists = Directory.Exists(string path); // Creates a directory (creates intermediate directories recursively). Directory.CreateDirectory(string path); // Deletes an empty directory. Directory.Delete(string path); // Deletes a directory and all its contents recursively. Directory.Delete(string path, bool recursive); // Gets an array of file paths in a directory. string[] files = Directory.GetFiles(string path); string[] files = Directory.GetFiles(string path, string searchPattern); // Gets an array of subdirectory paths. string[] dirs = Directory.GetDirectories(string path); // Moves (renames) a directory. Directory.Move(string sourceDirName, string destDirName);
Method List
| Method | Description |
|---|---|
| Directory.Exists(path) | Returns true if a directory exists at the specified path. |
| Directory.CreateDirectory(path) | Creates the directory. Also creates any intermediate directories that do not exist. Does nothing if the directory already exists. |
| Directory.Delete(path) | Deletes an empty directory. Throws IOException if the directory has contents. |
| Directory.Delete(path, true) | Deletes the directory and all its contents recursively. |
| Directory.GetFiles(path) | Returns an array of full file paths in the directory. |
| Directory.GetFiles(path, pattern) | Returns a filtered list of files matching a pattern such as "*.txt". |
| Directory.GetDirectories(path) | Returns an array of full subdirectory paths in the directory. |
| Directory.Move(src, dest) | Moves a directory to a new location. Also used for renaming. |
Sample Code
Program.cs
using System;
using System.IO;
string basePath = "work";
string subPath = Path.Combine(basePath, "logs", "2024");
Console.WriteLine(Directory.Exists(basePath)); // False
// Creates the directory including intermediate paths (logs/2024) in one call.
Directory.CreateDirectory(subPath);
Console.WriteLine(Directory.Exists(subPath)); // True
// Creates test files.
File.WriteAllText(Path.Combine(subPath, "app.log"), "app log");
File.WriteAllText(Path.Combine(subPath, "error.log"), "error log");
File.WriteAllText(Path.Combine(subPath, "data.txt"), "data file");
// Gets all files in the directory.
Console.WriteLine("--- All files ---");
foreach (string file in Directory.GetFiles(subPath))
{
Console.WriteLine(Path.GetFileName(file));
}
// Filters by pattern (*.log only).
Console.WriteLine("--- .log files only ---");
foreach (string file in Directory.GetFiles(subPath, "*.log"))
{
Console.WriteLine(Path.GetFileName(file));
}
// Gets subdirectories.
Console.WriteLine("--- Subdirectories ---");
foreach (string dir in Directory.GetDirectories(basePath))
{
Console.WriteLine(Path.GetFileName(dir));
}
// Deletes the directory and all its contents recursively.
Directory.Delete(basePath, recursive: true);
Console.WriteLine($"After delete: {Directory.Exists(basePath)}"); // False
Run the following command:
dotnet script directory_exists_createdirectory.csx False True --- All files --- app.log data.txt error.log --- .log files only --- app.log error.log --- Subdirectories --- logs After delete: False
Practical Pattern: Recursive File Search
Using SearchOption.AllDirectories retrieves all files including those in subdirectories in a single call.
RecursiveSearch.cs
using System;
using System.IO;
Directory.CreateDirectory("project/src");
Directory.CreateDirectory("project/assets");
File.WriteAllText("project/src/main.cs", "// main");
File.WriteAllText("project/src/helper.cs", "// helper");
File.WriteAllText("project/assets/icon.png", "png data");
File.WriteAllText("project/readme.txt", "README");
// SearchOption.TopDirectoryOnly (default): top-level files only
Console.WriteLine("--- TopDirectoryOnly ---");
foreach (string f in Directory.GetFiles("project", "*", SearchOption.TopDirectoryOnly))
Console.WriteLine(Path.GetFileName(f));
// SearchOption.AllDirectories: includes subdirectories
Console.WriteLine("--- AllDirectories ---");
foreach (string f in Directory.GetFiles("project", "*", SearchOption.AllDirectories))
Console.WriteLine(Path.GetRelativePath("project", f));
// Collects only .cs files recursively.
Console.WriteLine("--- .cs files ---");
foreach (string f in Directory.GetFiles("project", "*.cs", SearchOption.AllDirectories))
Console.WriteLine(Path.GetFileName(f));
// Cleanup.
Directory.Delete("project", recursive: true);
Run the following command:
dotnet script recursive_search.csx --- TopDirectoryOnly --- readme.txt --- AllDirectories --- readme.txt src/main.cs src/helper.cs assets/icon.png --- .cs files --- main.cs helper.cs
Practical Pattern: Backup Directory Management
A pattern for creating dated backup directories and automatically removing old ones.
BackupManager.cs
using System;
using System.IO;
using System.Linq;
string backupRoot = "backups";
Directory.CreateDirectory(backupRoot);
// Creates today's backup directory.
string todayDir = Path.Combine(backupRoot, DateTime.Today.ToString("yyyyMMdd"));
Directory.CreateDirectory(todayDir);
File.WriteAllText(Path.Combine(todayDir, "data.bak"), "backup data");
Console.WriteLine($"Backup created: {todayDir}");
// Deletes backups that are 7 or more days old.
string[] dirs = Directory.GetDirectories(backupRoot);
foreach (string dir in dirs)
{
string dirName = Path.GetFileName(dir);
if (DateTime.TryParseExact(dirName, "yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out DateTime dirDate))
{
int age = (DateTime.Today - dirDate).Days;
if (age >= 7)
{
Directory.Delete(dir, recursive: true);
Console.WriteLine($"Deleted: {dirName} ({age} days old)");
}
else
{
Console.WriteLine($"Kept: {dirName} ({age} days old)");
}
}
}
// Cleanup.
Directory.Delete(backupRoot, recursive: true);
Run the following command:
dotnet script backup_manager.csx Backup created: backups/20240115 Kept: 20240115 (0 days old)
Common Mistakes
Common Mistake 1: Calling Delete() on a Non-Empty Directory
Directory.Delete(path) only works on empty directories. If the directory has contents, an IOException is thrown.
using System;
using System.IO;
Directory.CreateDirectory("testdir");
File.WriteAllText("testdir/file.txt", "data");
// NG: Throws IOException because the directory is not empty.
Directory.Delete("testdir");
Run the following command:
dotnet run Unhandled exception. System.IO.IOException: The directory is not empty. : 'testdir'
The following example demonstrates this:
using System;
using System.IO;
Directory.CreateDirectory("testdir");
File.WriteAllText("testdir/file.txt", "data");
// OK: Pass recursive: true to delete the contents as well.
Directory.Delete("testdir", recursive: true);
Console.WriteLine("Deleted.");
Run the following command:
dotnet run Deleted.
Common Mistake 2: Building Paths by String Concatenation
Manually concatenating paths can fail because the path separator differs between operating systems. Always use Path.Combine().
using System;
using System.IO;
// NG: "/" works on macOS/Linux but may cause issues on Windows.
string bad = "work" + "/" + "logs";
// OK: Path.Combine() uses the correct OS separator automatically.
string good = Path.Combine("work", "logs");
Console.WriteLine(good); // Windows: work\logs / macOS/Linux: work/logs
Overview
Directory.CreateDirectory() does not throw an exception if the directory already exists, so there is no need to check with Exists() beforehand. Recursive deletion with Directory.Delete(path, true) is irreversible, so verify the path carefully before running it.
For building path strings, use Path.Combine() / Path.GetFileName(), which handles OS-specific separator differences automatically. For reading and writing files, see File.ReadAllText() / WriteAllText().
If you find any errors or copyright issues, please contact us.