System.IO.Directory Class
Overview
The System.IO.Directory
class provides static methods for creating, moving, and enumerating through directories and subdirectories. It also offers functionality to retrieve information about the file system directories.
Key Methods
Creates all directories and subdirectories in the specified path.
Deletes an empty directory or a directory with its contents.
Returns an enumerable collection of file names in a directory.
Gets the names of files (including their paths) in the specified directory.
Retrieves the names of subdirectories (including their paths) in the specified directory.
Determines whether the given path refers to an existing directory.
Moves a directory and its contents to a new location.
Gets the current working directory of the application.
Sets the application's current working directory.
Usage Example
The following C# example demonstrates how to create a directory, list its files, and delete it safely.
using System;
using System.IO;
class DirectoryDemo
{
static void Main()
{
string path = @"C:\Temp\DemoFolder";
// Create directory if it does not exist
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
Console.WriteLine($"Created: {path}");
}
// Create a sample file inside the directory
string filePath = Path.Combine(path, "sample.txt");
File.WriteAllText(filePath, "Hello, Directory!");
// List files in the directory
Console.WriteLine("Files in directory:");
foreach (var file in Directory.GetFiles(path))
{
Console.WriteLine($" - {Path.GetFileName(file)}");
}
// Clean up
File.Delete(filePath);
Directory.Delete(path);
Console.WriteLine("Cleaned up.");
}
}