C-SHARP - 5.4 Directory and DirectoryInfo

The Directory and DirectoryInfo classes from the System.IO namespace let you work with folders in C#. Just like with files, there are two approaches: static (Directory) and object-oriented (DirectoryInfo).

The Directory class: static operations

Directory exposes static methods for one-off operations: creating a folder, checking whether it exists, deleting it, moving it, or listing its contents.

using System.IO;

if (!Directory.Exists("myFolder"))
{
    Directory.CreateDirectory("myFolder");
}

string[] files = Directory.GetFiles("myFolder");
string[] subFolders = Directory.GetDirectories("myFolder");

Directory.Move("old", "new");
Directory.Delete("toDelete", recursive: true);

Important note: by default Directory.Delete only removes an empty folder. Pass recursive: true to also delete everything inside it.

The DirectoryInfo class: object-oriented approach

DirectoryInfo treats a folder as an object, which is preferable as soon as you're chaining several operations on the same folder. You access properties directly (Name, FullName, Parent, CreationTime, Exists) without having to pass the path on every call.

DirectoryInfo folder = new DirectoryInfo("projects");
Console.WriteLine(folder.Name);
Console.WriteLine(folder.CreationTime);
foreach (FileInfo f in folder.GetFiles())
{
    Console.WriteLine(f.Name + " - " + f.Length + " bytes");
}
foreach (DirectoryInfo sd in folder.GetDirectories())
{
    Console.WriteLine(sd.Name);
}

Which approach should you choose?

For a one-off check or a single create/delete, Directory is more direct. To explore a folder structure in depth, list files and subfolders, or chain several operations, DirectoryInfo makes the code more natural and more efficient. Both classes are essential for any application that needs to organize, scan, or clean up a file tree.