C# System.IO
Working with files and directories
📁 What is System.IO?
System.IO provides classes for reading and writing files, creating directories, and managing the file system. It enables your programs to save data, load configurations, and interact with files on your computer.
// Simple file writing
using System.IO;
File.WriteAllText("message.txt", "Hello, File!");
string content = File.ReadAllText("message.txt");
Core System.IO Classes
File
Read and write files
File.WriteAllText("file.txt", "data");
File.ReadAllText("file.txt");
Directory
Manage folders
Directory.CreateDirectory("folder");
Directory.GetFiles("folder");
Path
Handle file paths
Path.Combine("folder", "file.txt");
Path.GetExtension("file.txt");
StreamWriter
Write text streams
using var writer = new StreamWriter("log.txt");
writer.WriteLine("Log entry");
🔹 Reading and Writing Files
The File class in C# provides streamlined, one-step methods for synchronous file operations, simplifying reading and writing entire files. Using `File.WriteAllText()` and `File.ReadAllText()`, developers can effortlessly save and load complete text content—ideal for configurations, logs, or small data stores. For example, writing "Hello from C#!" and "This is line 2." creates a file that can be read back line by line, with properties like existence and line count easily verified. This approach minimizes code complexity for straightforward file tasks while ensuring reliability and ease of use.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Write text to file
string content = "Hello from C#!\nThis is line 2.";
File.WriteAllText(filePath, content);
Console.WriteLine("File written successfully!");
// Read text from file
string readContent = File.ReadAllText(filePath);
Console.WriteLine("\nFile content:");
Console.WriteLine(readContent);
// Append text to file
File.AppendAllText(filePath, "\nAppended line.");
// Read all lines as array
string[] lines = File.ReadAllLines(filePath);
Console.WriteLine($"\nTotal lines: {lines.Length}");
// Check if file exists
bool exists = File.Exists(filePath);
Console.WriteLine($"File exists: {exists}");
}
}
Output:
File written successfully!
File content:
Hello from C#!
This is line 2.
Total lines: 3
File exists: True
🔹 Working with Directories
The Directory class in C# enables programmatic management of folder structures, supporting creation, deletion, and traversal of directories. Methods like `CreateDirectory()`, `Exists()`, and `GetFiles()` allow seamless organization of file systems—useful for setting up project folders, logs, or user data. For instance, creating "MyFolder," verifying its existence, and listing contents (e.g., "test.txt") helps automate data organization. Additionally, enumerating subdirectories aids in recursive operations, making Directory essential for applications that require dynamic folder handling, backup systems, or structured storage.
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = "MyFolder";
// Create directory
Directory.CreateDirectory(folderPath);
Console.WriteLine($"Created directory: {folderPath}");
// Check if directory exists
bool exists = Directory.Exists(folderPath);
Console.WriteLine($"Directory exists: {exists}");
// Create a file in the directory
string filePath = Path.Combine(folderPath, "test.txt");
File.WriteAllText(filePath, "Test content");
// Get all files in directory
string[] files = Directory.GetFiles(folderPath);
Console.WriteLine($"\nFiles in {folderPath}:");
foreach (string file in files)
{
Console.WriteLine($"- {Path.GetFileName(file)}");
}
// Get all subdirectories
string[] dirs = Directory.GetDirectories(".");
Console.WriteLine($"\nSubdirectories: {dirs.Length}");
// Delete directory (must be empty or use recursive)
// Directory.Delete(folderPath, true);
}
}
Output:
Created directory: MyFolder
Directory exists: True
Files in MyFolder:
- test.txt
Subdirectories: 3
🔹 Path Operations
The Path class offers cross-platform, safe manipulation of file and directory paths, preventing common errors and ensuring OS compatibility. It combines path segments correctly, extracts components like file names and extensions, and resolves system-specific temp folders. For example, from "Documents\document.txt," Path can isolate "document.txt," retrieve the ".txt" extension, or change it to ".pdf." It also provides the temporary directory path (e.g., "C:\Users\...\Temp\"). This eliminates manual string parsing, reduces bugs from slashes or invalid characters, and enhances portability across Windows, Linux, and macOS environments.
using System;
using System.IO;
class Program
{
static void Main()
{
string fileName = "document.txt";
string folder = "Documents";
// Combine paths safely
string fullPath = Path.Combine(folder, fileName);
Console.WriteLine($"Full path: {fullPath}");
// Get file name
string name = Path.GetFileName(fullPath);
Console.WriteLine($"File name: {name}");
// Get file extension
string extension = Path.GetExtension(fullPath);
Console.WriteLine($"Extension: {extension}");
// Get file name without extension
string nameOnly = Path.GetFileNameWithoutExtension(fullPath);
Console.WriteLine($"Name only: {nameOnly}");
// Get directory name
string directory = Path.GetDirectoryName(fullPath);
Console.WriteLine($"Directory: {directory}");
// Change extension
string newPath = Path.ChangeExtension(fullPath, ".pdf");
Console.WriteLine($"New path: {newPath}");
// Get temp path
string tempPath = Path.GetTempPath();
Console.WriteLine($"Temp folder: {tempPath}");
}
}
Output:
Full path: Documents\document.txt
File name: document.txt
Extension: .txt
Name only: document
Directory: Documents
New path: Documents\document.pdf
Temp folder: C:\Users\User\AppData\Local\Temp\
🔹 StreamWriter and StreamReader
StreamWriter and StreamReader handle efficient, line-by-line file I/O in C#, optimizing memory usage for large files like logs or datasets. StreamWriter writes text incrementally, while StreamReader reads sequentially—ideal for appending logs, processing multi-gigabyte files, or real-time data streaming. For instance, creating a log with entries "Log entry 1," "Log entry 2," and appending new lines avoids loading the entire file into memory. This approach enhances performance and scalability, making these classes perfect for applications dealing with extensive text data, continuous logging, or batch processing.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "log.txt";
// Write using StreamWriter
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Log entry 1");
writer.WriteLine("Log entry 2");
writer.WriteLine("Log entry 3");
}
Console.WriteLine("Log file created!");
// Read using StreamReader
Console.WriteLine("\nReading log file:");
using (StreamReader reader = new StreamReader(filePath))
{
string line;
int lineNumber = 1;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine($"{lineNumber}: {line}");
lineNumber++;
}
}
// Append to file
using (StreamWriter writer = new StreamWriter(filePath, append: true))
{
writer.WriteLine("Log entry 4");
}
Console.WriteLine("\nAppended new entry!");
}
}
Output:
Log file created!
Reading log file:
1: Log entry 1
2: Log entry 2
3: Log entry 3
Appended new entry!
🔹 File Information
The file path and creation date provide essential metadata for organizing and tracking project files. Located at C:\Projects, the file was created on 9/15/2025 10:00:00 AM. This information helps developers identify file origins, manage version control, and debug issues by referencing timestamps and directory structures—crucial for collaborative software development and system administration tasks.
using System;
using System.IO;
class Program
{
static void Main()
{
// Create a test file
string filePath = "info.txt";
File.WriteAllText(filePath, "Sample content for testing.");
// Get file information
FileInfo fileInfo = new FileInfo(filePath);
Console.WriteLine("File Information:");
Console.WriteLine($"Name: {fileInfo.Name}");
Console.WriteLine($"Full path: {fileInfo.FullName}");
Console.WriteLine($"Size: {fileInfo.Length} bytes");
Console.WriteLine($"Created: {fileInfo.CreationTime}");
Console.WriteLine($"Modified: {fileInfo.LastWriteTime}");
Console.WriteLine($"Extension: {fileInfo.Extension}");
Console.WriteLine($"Read-only: {fileInfo.IsReadOnly}");
// Directory information
DirectoryInfo dirInfo = new DirectoryInfo(".");
Console.WriteLine($"\nCurrent directory: {dirInfo.Name}");
Console.WriteLine($"Full path: {dirInfo.FullName}");
Console.WriteLine($"Created: {dirInfo.CreationTime}");
}
}
Output:
File Information:
Name: info.txt
Full path: C:\Projects\info.txt
Size: 28 bytes
Created: 10/6/2025 2:30:00 PM
Modified: 10/6/2025 2:30:00 PM
Extension: .txt
Read-only: False
Current directory: Projects
Full path: C:\Projects
Created: 9/15/2025 10:00:00 AM