System.IO.Directory

The System.IO.Directory class provides static methods for creating, moving, and enumerating through directories and subdirectories.

Namespace

System.IO

Assembly

System.Runtime.dll

Overview
Methods
Properties
Examples

The Directory class contains methods for common directory operations such as creating, deleting, moving, and retrieving directory information. All methods are static, so you do not instantiate a Directory object.

Key Methods

  • bool Exists(string path) – Determines whether the given path refers to an existing directory.
  • void CreateDirectory(string path) – Creates all directories and subdirectories in the specified path.
  • string[] GetFiles(string path) – Returns the names of files (including their paths) in the specified directory.
  • string[] GetFiles(string path, string searchPattern) – Returns file names that match the search pattern.
  • string[] GetDirectories(string path) – Returns the names of subdirectories in the specified directory.
  • void Delete(string path, bool recursive) – Deletes the specified directory, optionally removing subdirectories and files.
  • void Move(string sourceDirName, string destDirName) – Moves a directory and its contents to a new location.
  • DateTime GetCreationTime(string path) – Retrieves the creation date and time of the specified directory.
  • void SetCreationTime(string path, DateTime creationTime) – Sets the creation date and time.

The Directory class does not expose instance properties because it is a static class. For property‑like information, use its methods such as GetCreationTime and GetLastWriteTime.

Creating a Directory

// Create a directory named "Logs" in the current folder
string dirPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs");
if (!Directory.Exists(dirPath))
{
    Directory.CreateDirectory(dirPath);
    Console.WriteLine($"Created: {dirPath}");
}

Listing Files Recursively

// List all *.txt files under a given folder recursively
string root = @"C:\MyApp\Data";
string[] txtFiles = Directory.GetFiles(root, "*.txt", SearchOption.AllDirectories);
foreach (var file in txtFiles)
{
    Console.WriteLine(file);
}

Deleting a Directory

// Delete a directory and all its contents
string oldLogs = @"C:\MyApp\Logs";
if (Directory.Exists(oldLogs))
{
    Directory.Delete(oldLogs, recursive: true);
    Console.WriteLine($"Deleted: {oldLogs}");
}