File and Directory Classes
Vaibhav • September 10, 2025
In the previous article, we introduced the concept of File I/O and saw how C# applications interact with the
file system to read and write data. Now we’ll take a deeper look at the core classes that make this possible -
File
, Directory
, and their related helpers in
the System.IO
namespace. These classes provide high-level, static methods to
perform common file and folder operations without needing to manage streams manually.
Working with the File Class
The File
class is your go-to utility for manipulating files. It provides static
methods to create, copy, delete, move, and read/write files. Let’s start with a few basic operations:
// Create a new file and write text
File.WriteAllText("hello.txt", "Hello, world!");
// Read the contents of a file
string content = File.ReadAllText("hello.txt");
Console.WriteLine(content); // Output: Hello, world!
// Check if a file exists
if (File.Exists("hello.txt"))
{
Console.WriteLine("File found.");
}
// Delete a file
File.Delete("hello.txt");
These methods are simple and efficient for small files. WriteAllText
and ReadAllText
handle opening and closing the file internally, which makes them
ideal for quick tasks.
If the file doesn’t exist, ReadAllText
will throw a
FileNotFoundException
. Always check with File.Exists
before reading.
Copying and Moving Files
You can copy or move files using File.Copy
and File.Move
. These methods are useful when organizing files or implementing backup
logic.
// Copy a file
File.Copy("source.txt", "backup.txt", overwrite: true);
// Move a file
File.Move("backup.txt", "archive/backup.txt");
The overwrite
parameter in File.Copy
lets you
control whether an existing destination file should be replaced. File.Move
will
fail if the destination file already exists.
Getting File Information
For more detailed metadata, use the FileInfo
class. Unlike File
, which is static, FileInfo
is
instance-based and provides properties like size, creation time, and extension.
FileInfo info = new FileInfo("data.txt");
Console.WriteLine($"Size: {info.Length} bytes");
Console.WriteLine($"Created: {info.CreationTime}");
Console.WriteLine($"Extension: {info.Extension}");
This is especially useful when building file explorers or logging file metadata.
FileInfo
caches data after the first access. If the
file changes, call info.Refresh()
to update the properties.
Working with the Directory Class
Just like File
, the Directory
class provides
static methods to manage folders. You can create, delete, move, and enumerate directories easily.
// Create a new directory
Directory.CreateDirectory("Logs");
// Check if a directory exists
if (Directory.Exists("Logs"))
{
Console.WriteLine("Logs folder is ready.");
}
// Delete a directory
Directory.Delete("Logs", recursive: true);
The recursive
flag allows deletion of non-empty directories. Without it, Directory.Delete
will throw an exception if the folder contains files.
Listing Files and Subdirectories
You can list the contents of a directory using Directory.GetFiles
and Directory.GetDirectories
. These return arrays of full paths.
// List all .txt files in a folder
string[] files = Directory.GetFiles("Documents", "*.txt");
foreach (string file in files)
{
Console.WriteLine(file);
}
// List all subdirectories
string[] folders = Directory.GetDirectories("Documents");
foreach (string folder in folders)
{
Console.WriteLine(folder);
}
You can use wildcards like *.txt
to filter results. This is useful for batch
processing or organizing files by type.
You can combine Directory.GetFiles
with
Path.GetFileName
to extract just the file name from the full path.
Getting Directory Information
Like FileInfo
, there’s a DirectoryInfo
class
for detailed folder metadata.
DirectoryInfo dir = new DirectoryInfo("Documents");
Console.WriteLine($"Created: {dir.CreationTime}");
Console.WriteLine($"Full Path: {dir.FullName}");
Console.WriteLine($"Parent: {dir.Parent}");
This is useful when building tools that need to navigate folder hierarchies or display folder properties.
Combining File and Directory Operations
Often, you’ll need to combine file and directory logic. For example, saving logs in a folder that may or may not exist:
string logFolder = "Logs";
string logFile = "Logs/log.txt";
if (!Directory.Exists(logFolder))
{
Directory.CreateDirectory(logFolder);
}
File.AppendAllText(logFile, $"Log entry at {DateTime.Now}\n");
This ensures your application doesn’t crash due to missing folders and keeps your file system organized.
Temporary Files and Directories
C# provides helpers to create temporary files and folders. These are useful for intermediate data or testing.
// Create a temp file
string tempFile = Path.GetTempFileName();
Console.WriteLine($"Temp file: {tempFile}");
// Create a temp folder
string tempFolder = Path.Combine(Path.GetTempPath(), "MyAppTemp");
Directory.CreateDirectory(tempFolder);
Temp files are automatically created with unique names. Use Path.GetTempPath
to
get the system’s temp directory.
Best Practices for File and Directory Usage
When working with files and folders, keep these practices in mind:
- Always check existence before reading or deleting.
- Use
Path.Combine
to build paths safely. - Wrap file operations in
try-catch
blocks to handle exceptions. - Use
Directory.CreateDirectory
even if the folder exists - it won’t throw. - Clean up temp files and folders after use.
Avoid hardcoding paths. Use Environment.GetFolderPath
with
Environment.SpecialFolder
to access user folders like Documents or Desktop.
Summary
The File
and Directory
classes are powerful
tools for managing the file system in C#. They provide simple, high-level methods for reading, writing, copying,
moving, and deleting files and folders. By combining these with FileInfo
and
DirectoryInfo
, you gain access to rich metadata and flexible control. In the
next article, we’ll explore how to read text files line-by-line and process their contents efficiently using
stream readers.