This C# File I/O Quick Reference Guide explores the core classes for handling files and directories.
Learn the difference between static utility classes (like File and Directory for simple, one-time operations) and instance classes (like FileInfoand DirectoryInfofor object-oriented access and metadata). The guide also covers Stream classes (StreamReader, StreamWriter, FileStream, etc.) for efficient data handling, along with utilities for path manipulation (Path) and monitoring (FileSystemWatcher).
Discover best practices and when to use each class for maximum performance.
File (Static Class)
What it is: Static utility class for quick file operations without creating objects.
Use: Best for simple, one-time file operations.
Key Methods
-
ReadAllText(path)- Read entire file as string -
WriteAllText(path, content)- Write string to file (overwrites) -
AppendAllText(path, content)- Add text to end of file -
ReadAllLines(path)- Read file as string array (line by line) -
WriteAllLines(path, lines)- Write array of strings as lines -
ReadAllBytes(path)- Read file as byte array -
WriteAllBytes(path, bytes)- Write byte array to file -
Copy(source, dest)- Copy file to new location -
Move(source, dest)- Move/rename file -
Delete(path)- Delete file -
Exists(path)- Check if file exists -
Create(path)- Create new file (returns FileStream)
FileInfo (Instance Class)
What it is: Object-oriented approach to file operations with metadata.
Use: When you need file properties or multiple operations on same file.
Key Properties
-
Name- File name with extension -
FullName- Complete path -
Extension- File extension (e.g., ".txt") -
DirectoryName- Parent directory path -
Directory- Parent DirectoryInfo object -
Length- File size in bytes -
CreationTime- When file was created -
LastWriteTime- When last modified -
LastAccessTime- When last accessed -
Exists- Boolean if file exists -
IsReadOnly- Boolean if read-only
Key Methods
-
Create()- Create file (returns FileStream) -
Open(FileMode)- Open with specified mode -
OpenRead()- Open for reading -
OpenWrite()- Open for writing -
Delete()- Delete file -
CopyTo(dest)- Copy to destination -
MoveTo(dest)- Move to destination -
Refresh()- Update cached info
Directory (Static Class)
What it is: Static utility for directory operations.
Use: Quick directory tasks without creating objects.
Key Methods
-
Exists(path)- Check if directory exists -
Create(path)- Create directory (creates parent dirs too) -
Delete(path, recursive)- Delete directory -
Move(source, dest)- Move/rename directory -
GetFiles(path)- Get file paths in directory -
GetFiles(path, pattern)- Get matching files (e.g., "*.txt") -
GetDirectories(path)- Get subdirectory paths -
GetFileSystemEntries(path)- Get both files and dirs -
GetCurrentDirectory()- Get current working directory -
SetCurrentDirectory(path)- Change working directory -
GetParent(path)- Get parent directory info -
EnumerateFiles(path)- Lazy enumeration of files (memory efficient)
DirectoryInfo (Instance Class)
What it is: Object-oriented directory operations with metadata.
Use: When you need directory properties or multiple operations.
Key Properties
-
Name- Directory name -
FullName- Complete path -
Parent- Parent DirectoryInfo object -
Root- Root DirectoryInfo (e.g., C:) -
Exists- Boolean if directory exists -
CreationTime- When created -
LastWriteTime- When last modified -
LastAccessTime- When last accessed
Key Methods
-
Create()- Create directory -
CreateSubdirectory(name)- Create subdirectory -
Delete()/Delete(recursive)- Delete directory -
MoveTo(dest)- Move directory -
GetFiles()- Get FileInfo array -
GetFiles(pattern)- Get matching FileInfo objects -
GetDirectories()- Get subdirectory array -
GetFileSystemInfos()- Get both files and dirs -
EnumerateFiles()- Lazy enumeration
StreamReader
What it is: Reads text files efficiently line-by-line or character-by-character.
Use: Reading large text files without loading entire file into memory.
Key Properties
-
EndOfStream- Boolean if reached end of file
Key Methods
-
Read()- Read single character (returns int, -1 at end) -
ReadLine()- Read one line as string (null at end) -
ReadToEnd()- Read rest of file as string -
ReadBlock(buffer, index, count)- Read into char array -
Close()- Close stream -
Dispose()- Release resources (use withusing)
Usage Example
using (StreamReader sr = new StreamReader("file.txt"))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
}
}
StreamWriter
What it is: Writes text to files efficiently.
Use: Writing large amounts of text incrementally.
Key Properties
-
AutoFlush- Boolean, if true writes immediately (default false)
Key Methods
-
Write(value)- Write without newline -
WriteLine(value)- Write with newline -
Flush()- Force write buffered data to file -
Close()- Close stream -
Dispose()- Release resources
Usage Example
using (StreamWriter sw = new StreamWriter("file.txt"))
{
sw.WriteLine("First line");
sw.WriteLine("Second line");
}
BinaryReader
What it is: Reads primitive data types in binary format.
Use: Reading binary files or serialized data.
Key Methods
-
ReadBoolean()- Read bool -
ReadByte()- Read single byte -
ReadBytes(count)- Read byte array -
ReadInt32()- Read 4-byte integer -
ReadInt64()- Read 8-byte long -
ReadDouble()- Read 8-byte double -
ReadString()- Read length-prefixed string -
ReadChar()- Read single character -
Close()/Dispose()- Release resources
BinaryWriter
What it is: Writes primitive data types in binary format.
Use: Writing binary data or serialization.
Key Methods
-
Write(bool)- Write boolean -
Write(byte)- Write single byte -
Write(byte[])- Write byte array -
Write(int)- Write 4-byte integer -
Write(long)- Write 8-byte long -
Write(double)- Write 8-byte double -
Write(string)- Write length-prefixed string -
Flush()- Force write buffered data -
Close()/Dispose()- Release resources
FileStream
What it is: Low-level stream for reading/writing bytes to files.
Use: Maximum control over file operations, binary data, or as base for other streams.
Key Properties
-
Length- File size in bytes -
Position- Current position in stream -
CanRead- Boolean if can read -
CanWrite- Boolean if can write -
CanSeek- Boolean if can seek (change position)
Key Methods
-
Read(buffer, offset, count)- Read bytes into array -
Write(buffer, offset, count)- Write bytes from array -
ReadByte()- Read single byte -
WriteByte(byte)- Write single byte -
Seek(offset, origin)- Change position in stream -
Flush()- Write buffered data to disk -
SetLength(length)- Truncate or extend file -
Close()/Dispose()- Release resources
Constructor
FileStream fs = new FileStream(path, FileMode, FileAccess, FileShare);
FileMode (Enum)
What it is: Specifies how to open a file.
Use: Pass to FileStream constructor or File.Open().
Values
-
CreateNew- Create new file (error if exists) -
Create- Create new file (overwrites if exists) -
Open- Open existing file (error if doesn't exist) -
OpenOrCreate- Open if exists, create if doesn't -
Truncate- Open and clear contents (error if doesn't exist) -
Append- Open and seek to end (creates if doesn't exist)
FileAccess (Enum)
What it is: Defines read/write permissions.
Use: Control access level when opening files.
Values
-
Read- Read-only access -
Write- Write-only access -
ReadWrite- Both read and write
FileShare (Enum)
What it is: Controls how other processes can access the file while you have it open.
Use: Allow/prevent concurrent access.
Values
-
None- No sharing (exclusive access) -
Read- Others can read -
Write- Others can write -
ReadWrite- Others can read and write -
Delete- Others can delete -
Inheritable- Handle can be inherited by child processes
BufferedStream
What it is: Wraps another stream to add buffering for better performance.
Use: Improve performance when doing many small reads/writes.
Key Methods
-
Read(buffer, offset, count)- Read bytes -
Write(buffer, offset, count)- Write bytes -
Flush()- Write buffer to underlying stream -
Close()/Dispose()- Release resources
Usage Example
using (FileStream fs = new FileStream("file.bin", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
{
// Faster reads/writes due to buffering
}
DriveInfo (Instance Class)
What it is: Information about disk drives.
Use: Get drive capacity, type, and availability.
Key Properties
-
Name- Drive letter (e.g., "C:\") -
DriveType- Type (Fixed, Removable, Network, CDRom, etc.) -
DriveFormat- File system (e.g., "NTFS", "FAT32") -
TotalSize- Total space in bytes -
TotalFreeSpace- Available free space in bytes -
AvailableFreeSpace- Free space available to current user -
VolumeLabel- Drive label (can be set) -
IsReady- Boolean if drive is ready/available -
RootDirectory- Root DirectoryInfo
Static Method
-
GetDrives()- Returns array of all drives
Usage Example
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
if (d.IsReady)
Console.WriteLine($"{d.Name}: {d.TotalFreeSpace} bytes free");
}
MemoryStream
What it is: Stream that uses memory (RAM) instead of a file.
Use: In-memory buffer for temporary data or converting between streams and byte arrays.
Key Properties
-
Length- Number of bytes -
Capacity- Allocated memory size -
Position- Current position
Key Methods
-
Read(buffer, offset, count)- Read bytes -
Write(buffer, offset, count)- Write bytes -
ToArray()- Get contents as byte array -
WriteTo(stream)- Copy to another stream -
GetBuffer()- Get underlying byte array (faster but unsafe) -
SetLength(length)- Change length -
Close()/Dispose()- Release resources
Usage Example
using (MemoryStream ms = new MemoryStream())
{
byte[] data = { 1, 2, 3, 4 };
ms.Write(data, 0, data.Length);
byte[] result = ms.ToArray();
}
Path (Static Class)
What it is: Utility for working with file and directory path strings.
Use: Safely combine, parse, and manipulate paths.
Key Methods
-
Combine(path1, path2)- Join paths with correct separator -
GetFileName(path)- Get file name with extension -
GetFileNameWithoutExtension(path)- Get file name only -
GetExtension(path)- Get extension (e.g., ".txt") -
GetDirectoryName(path)- Get directory portion -
GetFullPath(path)- Convert relative to absolute path -
GetPathRoot(path)- Get root (e.g., "C:\") -
GetTempPath()- Get system temp directory -
GetTempFileName()- Create unique temp file name -
GetRandomFileName()- Generate random file name -
HasExtension(path)- Check if path has extension -
IsPathRooted(path)- Check if absolute path -
ChangeExtension(path, ext)- Replace extension
Key Fields
-
DirectorySeparatorChar- '\' on Windows, '/' on Unix -
AltDirectorySeparatorChar- Alternate separator -
PathSeparator- ';' on Windows, ':' on Unix (for PATH env variable)
StringReader
What it is: Reads from a string as if it were a stream.
Use: Parse strings line-by-line using stream methods.
Key Methods
-
Read()- Read single character -
ReadLine()- Read line from string -
ReadToEnd()- Read rest of string -
Close()/Dispose()- Release resources
Usage Example
string data = "Line 1\nLine 2\nLine 3";
using (StringReader sr = new StringReader(data))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
StringWriter
What it is: Writes to a StringBuilder as if it were a stream.
Use: Build strings using stream writing methods.
Key Methods
-
Write(value)- Write without newline -
WriteLine(value)- Write with newline -
ToString()- Get resulting string -
Close()/Dispose()- Release resources
Usage Example
using (StringWriter sw = new StringWriter())
{
sw.WriteLine("Line 1");
sw.WriteLine("Line 2");
string result = sw.ToString();
}
Additional Important Classes
FileSystemWatcher
What it is: Monitors file system for changes.
Use: Detect when files/directories are created, changed, renamed, or deleted.
Key Properties
-
Path- Directory to watch -
Filter- File filter (e.g., "*.txt") -
NotifyFilter- What changes to watch (FileName, Size, LastWrite, etc.) -
IncludeSubdirectories- Watch subdirectories too -
EnableRaisingEvents- Start/stop watching
Key Events
-
Created- File/directory created -
Changed- File/directory changed -
Deleted- File/directory deleted -
Renamed- File/directory renamed -
Error- Error occurred
StreamReader/StreamWriter with Encoding
Tip: Both classes support encoding for different character sets.
// UTF-8 with BOM
new StreamReader("file.txt", Encoding.UTF8);
// ASCII
new StreamWriter("file.txt", false, Encoding.ASCII);
Quick Comparison Guide
File vs FileInfo
- File: Static, one-liner operations, no object creation
- FileInfo: Instance-based, reusable, has properties, better for multiple ops
Directory vs DirectoryInfo
- Directory: Static, quick operations
- DirectoryInfo: Instance-based, has properties, better for multiple ops
When to Use What
-
Simple text read/write:
File.ReadAllText()/File.WriteAllText() -
Large text files line-by-line:
StreamReader/StreamWriter -
Binary data:
BinaryReader/BinaryWriter -
Maximum control:
FileStream -
In-memory data:
MemoryStream -
String parsing:
StringReader/StringWriter -
Performance for small ops:
BufferedStream -
Path manipulation:
Pathclass -
File monitoring:
FileSystemWatcher
Best Practices
-
Always use
usingstatements for streams to ensure proper disposal - Use Path.Combine() instead of string concatenation
- Check File.Exists() or Directory.Exists() before operations
- Handle exceptions (IOException, UnauthorizedAccessException, etc.)
-
Use async methods (.NET 4.5+) for better performance:
ReadAsync(),WriteAsync() - StreamReader/Writer for text, BinaryReader/Writer for binary
- Prefer File/Directory static methods for simple operations
- Use FileInfo/DirectoryInfo when you need properties or multiple operations
Top comments (0)