Working with the File System in C#: From Basics to Advanced Techniques
Working with the file system is one of the key tasks when developing applications in C#. Whether it's saving user data, reading configuration files, or processing logs — the ability to effectively interact with files and directories is essential for every .NET developer. In this article, we will cover the main classes of the System.IO namespace, learn how to create, read, and modify files, and also look at best practices for error handling.
1. Main Classes for Working with the File System
In .NET, several key classes are provided for working with files and directories. Let's look at them in detail.
File and FileInfo Classes
File is a static class that provides methods for creating, copying, deleting, and moving files. FileInfo is an instance class that allows you to work with a specific file.
using System.IO;
// Using the static File classstring path = @"C:\\Temp\\test.txt";if (File.Exists(path)){ string content = File.ReadAllText(path); Console.WriteLine(content);}
// Using FileInfoFileInfo fileInfo = new FileInfo(path);if (fileInfo.Exists){ Console.WriteLine($"File size: {fileInfo.Length} bytes"); Console.WriteLine($"Creation date: {fileInfo.CreationTime}");}Directory and DirectoryInfo Classes
Similarly, Directory is a static class for operations with directories, and DirectoryInfo is for working with a specific folder.
string dirPath = @"C:\\Temp\\MyFolder";
// Creating a directoryDirectory.CreateDirectory(dirPath);
// Getting information about a directoryDirectoryInfo dirInfo = new DirectoryInfo(dirPath);if (dirInfo.Exists){ Console.WriteLine($"Subdirectories: {dirInfo.GetDirectories().Length}"); Console.WriteLine($"Files: {dirInfo.GetFiles().Length}");}Path Class
Path is a utility class for working with paths. It helps combine paths, extract extensions, and file names.
string fullPath = @"C:\\Temp\\myfile.txt";string fileName = Path.GetFileName(fullPath); // myfile.txtstring extension = Path.GetExtension(fullPath); // .txtstring directory = Path.GetDirectoryName(fullPath); // C:\\Tempstring combined = Path.Combine(@"C:\\Temp", "newfile.txt"); // C:\\Tempewfile.txt2. Reading and Writing Files
In C#, there are several ways to read and write files. The choice depends on the data size and required performance.
Reading Text Files
For small files, it is convenient to use one-line methods:
// Reading the entire file in one linestring text = File.ReadAllText("data.txt");
// Reading all lines into an arraystring[] lines = File.ReadAllLines("data.txt");
// Reading using StreamReader (for large files)using (StreamReader reader = new StreamReader("largefile.txt")){ string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); }}Writing to Files
// Writing a stringFile.WriteAllText("output.txt", "Hello, World!");
// Writing an array of stringsstring[] lines = { "First line", "Second line" };File.WriteAllLines("output.txt", lines);
// Appending to the end of a fileFile.AppendAllText("log.txt", $"{DateTime.Now}: New entry");
// Writing using StreamWriterusing (StreamWriter writer = new StreamWriter("data.txt", append: true)){ writer.WriteLine("New line");}Working with Binary Files
For binary data, use FileStream and BinaryReader/BinaryWriter:
// Writing binary datausing (BinaryWriter writer = new BinaryWriter(File.Open("data.bin"