Working with the File System in C#: A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

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 any application. In C# (.NET), there is a powerful namespace System.IO for this purpose, which provides the developer with a complete set of tools for creating, reading, writing, moving, and deleting files and folders. In this article, we will thoroughly examine all the basic operations with the file system, starting with simple examples and ending with advanced data processing techniques.



Basics of Working with Files in C#



The System.IO namespace includes the File and FileInfo classes, which provide static and instance methods for managing files. Let's look at the basic operations.



Reading and Writing Text Files



The simplest way to work with text files is to use the static methods of the File class:



using System.IO;

// Writing text to a file (creates a new file or overwrites an existing one)string content = "Hello, world! This is an example of working with files in C#.";File.WriteAllText(@"C:\\temp\\example.txt", content);

// Reading all text from a filestring readContent = File.ReadAllText(@"C:\\temp\\example.txt");Console.WriteLine(readContent);

// Appending to the end of a fileFile.AppendAllText(@"C:\\temp\\example.txt", "New line added.");


Working with Binary Files



For working with binary data, use File.ReadAllBytes and File.WriteAllBytes:



byte[] binaryData = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F };File.WriteAllBytes(@"C:\\temp\\binary.bin", binaryData);

byte[] readBinary = File.ReadAllBytes(@"C:\\temp\\binary.bin");Console.WriteLine(string.Join(", ", readBinary)); // Output: 72, 101, 108, 108, 111


Checking File Existence and Deleting It



Before performing operations on files, it is always useful to check their existence:



string filePath = @"C:\\temp\\example.txt";

if (File.Exists(filePath)){ Console.WriteLine("File exists. Deleting..."); File.Delete(filePath); Console.WriteLine("File deleted.");}else{ Console.WriteLine("File not found.");}


Working with Directories in C#



The Directory and DirectoryInfo classes are used to manage folders. They allow you to create, move, rename, and delete directories, as well as obtain information about them.



Creating and Deleting Folders



string dirPath = @"C:\\temp\\MyNewFolder";

// Creating a folder (if it already exists, no exception is thrown)Directory.CreateDirectory(dirPath);

// Checking existenceif (Directory.Exists(dirPath)){ Console.WriteLine("Folder created successfully.");}

// Deleting a folder (second parameter - whether to delete recursively)Directory.Delete(dirPath, recursive: true);Console.WriteLine("Folder deleted.");


Getting a List of Files and Subfolders



The GetFiles and GetDirectories methods allow you to get the contents of a directory:



string targetDir = @"C:\\temp";

// Getting all files in the directorystring[] files = Directory.GetFiles(targetDir);Console.WriteLine("Files in the directory:");foreach (string file in files){ Console.WriteLine($" {Path.GetFileName(file)}");}

// Getting all subfoldersstring[] subDirs = Directory.GetDirectories(targetDir);Console.WriteLine("Subfolders:");foreach (string dir in subDirs){ Console.WriteLine($" {Path.GetFileName(dir)}");}

// Searching by pattern (e.g., all text files)string[] txtFiles = Directory.GetFiles(targetDir, "*.txt");Console.WriteLine($"Found {txtFiles.Length} text files.");


Working with DirectoryInfo



The DirectoryInfo class provides an instance-based approach for working with directories:

Blogs

Book Recommendations