Introduction: Why Working with the File System in C# is Necessary
\nAny serious application will sooner or later face the need to save data. Whether it's configuration files, logs, user documents, or temporary data — working with the file system is a fundamental skill for a C# developer. In this article, we will use practical examples to examine how to create, read, write, and manage files and folders using .NET. You will learn not only basic operations but also best practices for exception handling and working with streams.
\n\nMain Classes for Working with the File System
\nIn .NET, the System.IO and System.IO.Enumeration namespaces are used to interact with the file system. The key classes you will need are:
- \n
File— static methods for creating, copying, deleting, and moving files. \n FileInfo— an instance class for working with a specific file (supports the same operations but requires creating an object). \n Directory— static methods for working with directories. \n DirectoryInfo— an instance class for working with directories. \n Path— a utility class for working with paths (combining, getting extension, name, etc.). \n FileStream— a low-level stream for reading/writing bytes. \n StreamReader/StreamWriter— high-level wrappers for working with text. \n
The choice between static methods and instance classes depends on the scenario. If you need to perform a single operation — use File or Directory. If multiple operations are planned on the same object — create a FileInfo or DirectoryInfo.
Creating, Reading, and Writing Files
\n\n1. Creating and Writing a Text File
\nThe simplest way to write text to a file is to use the File.WriteAllText method. It creates the file (or overwrites an existing one) and closes the stream automatically.
using System.IO;\n\nstring path = @"C:\\temp\\example.txt";\nstring content = "Hello, world! This is a test file.";\n\nFile.WriteAllText(path, content);\nConsole.WriteLine("File created and written.");\nIf you need to append data to the end of a file, use File.AppendAllText:
File.AppendAllText(path, "\\nAppended line.");\n\n2. Reading a File
\nTo read the entire text, use File.ReadAllText:
string readContent = File.ReadAllText(path);\nConsole.WriteLine(readContent);\nIf the file is large, it's better to read it line by line using File.ReadLines (returns IEnumerable<string>):
foreach (string line in File.ReadLines(path))\n{\n Console.WriteLine(line);\n}\n\n3. Working with Binary Files
\nFor binary data (images, archives), use FileStream or BinaryReader/BinaryWriter. Example of writing a byte array:
byte[] data = { 0x48, 0x65, 0x6C, 0x6C, 0x6F }; // "Hello"\nFile.WriteAllBytes(@"C:\\temp\\binary.dat", data);\n\nbyte[] readData = File.ReadAllBytes(@"C:\\temp\\binary.dat");\nConsole.WriteLine(BitConverter.ToString(readData)); // 48-65-6C-6C-6F\n\nWorking with Folders and File Management
\n\n1. Creating and Deleting Folders
\nYou can create a folder using Directory.CreateDirectory. The method creates all missing folders in the path:
string dirPath = @"C:\\temp\\MyApp\\Logs";\nDirectory.CreateDirectory(dirPath);\nConsole.WriteLine("Folder created.");\nDeleting a folder (recursively, with all contents):
\nif (Directory.Exists(dirPath))\n{\n Directory.Delete(dirPath, true);\n Console.WriteLine("Folder deleted.");\n}\n\n2. Copying and Moving Files
\nTo copy a file, use File.Copy. The third parameter allows overwriting an existing file:
string sourceFile = @"C:\\temp\\example.txt";\nstring destFile = @"C:\\temp\\backup\\example.txt";\n\nDirectory.CreateDirectory(Path.GetDirectoryName(destFile));\nFile.Copy(sourceFile, destFile, overwrite: true);\nConsole.WriteLine("File copied.");\nTo move a file, use File.Move:
string movedFile = @"C:\\temp\\archive\\example.txt";\nDirectory.CreateDirectory(Path.GetDirectoryName(movedFile));\nFile.Move(sourceFile, movedFile);\nConsole.WriteLine("File moved.");\n\nWorking with Paths
\nThe Path class provides convenient methods for working with file paths. Examples:
string fullPath = @"C:\\temp\\MyApp\\Logs\\log.txt";\n\nConsole.WriteLine(Path.GetFileName(fullPath)); // log.txt\nConsole.WriteLine(Path.GetFileNameWithoutExtension(fullPath)); // log\nConsole.WriteLine(Path.GetExtension(fullPath)); // .txt\nConsole.WriteLine(Path.GetDirectoryName(fullPath)); // C:\\temp\\MyApp\\Logs\nConsole.WriteLine(Path.Combine(@"C:\\temp", "MyApp", "Logs", "log.txt")); // C:\\temp\\MyApp\\Logs\\log.txt\n\nException Handling
\nWhen working with the file system, various exceptions may occur. The main ones are:
\n- \n
FileNotFoundException— the file was not found. \n DirectoryNotFoundException— the directory was not found. \n UnauthorizedAccessException— insufficient access rights. \n IOException— a general I/O error (e.g., the file is already in use). \n PathTooLongException— the path exceeds the system limit. \n
Example of handling exceptions:
\ntry\n{\n string content = File.ReadAllText(@"C:\\temp\\missing.txt");\n Console.WriteLine(content);\n}\ncatch (FileNotFoundException)\n{\n Console.WriteLine("File not found.");\n}\ncatch (UnauthorizedAccessException)\n{\n Console.WriteLine("Access denied.");\n}\ncatch (IOException ex)\n{\n Console.WriteLine($"I/O error: {ex.Message}");\n}\n\nWorking with Streams
\nFor more flexible file handling, use streams. Example of reading a file using FileStream and StreamReader:
using (FileStream fs = new FileStream(@"C:\\temp\\example.txt", FileMode.Open, FileAccess.Read))\nusing (StreamReader reader = new StreamReader(fs))\n{\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n Console.WriteLine(line);\n }\n}\nExample of writing using StreamWriter:
using (StreamWriter writer = new StreamWriter(@"C:\\temp\\output.txt", append: false))\n{\n writer.WriteLine("First line.");\n writer.WriteLine("Second line.");\n}\nConsole.WriteLine("Recording completed.");\n\nConclusion
\nIn this article, we covered the basics of working with the file system in C#. You learned how to create, read, write files, manage folders, work with paths, and handle exceptions. These skills will be useful in almost any project — from small utilities to large enterprise applications. For further study, I recommend exploring the System.IO.Compression namespace for working with archives and System.IO.MemoryMappedFiles for efficient work with large files.