System.IO Namespace
The System.IO
namespace provides types that allow reading and writing files and data streams, and types that provide basic support for file and directory operations.
Key Concepts
- Streams: Sequential collection of bytes. Can be read from or written to. Examples include
FileStream
,MemoryStream
. - Readers and Writers: Helper classes for reading and writing text or binary data from/to streams, often with buffering for performance. Examples include
StreamReader
,StreamWriter
,BinaryReader
,BinaryWriter
. - File and Directory Operations: Classes and methods for interacting with the file system, such as creating, deleting, moving, and copying files and directories. Examples include
File
,Directory
,Path
. - I/O Exceptions: Specific exceptions related to input/output operations, such as
IOException
,FileNotFoundException
,DirectoryNotFoundException
.
Core Classes and Interfaces
Commonly Used Classes
Class Name | Description |
---|---|
FileStream |
Provides a stream for reading, writing, and seeking within a file. |
StreamReader |
Reads characters from a stream in a particular encoding. |
StreamWriter |
Writes characters to a stream in a particular encoding. |
MemoryStream |
Supports in-memory I/O. |
Path |
Provides methods for creating, manipulating, and resolving file and directory path strings. |
File |
Provides static methods for creating, copying, deleting, moving, and opening files. |
Directory |
Provides static methods for creating, moving, and enumerating through directories and subdirectories. |
Key Interfaces
Interface Name | Description |
---|---|
Stream |
Abstract base class for all streams. |
IDisposable |
Ensures that resources are released by implementing a mechanism for freeing unmanaged resources. Crucial for streams. |
Examples
Reading from a File
using System;
using System.IO;
public class FileReader
{
public static void Main(string[] args)
{
string filePath = "example.txt";
try
{
// Using statement ensures the StreamReader is disposed of properly.
using (StreamReader sr = new StreamReader(filePath))
{
string line;
// Read and display lines from the file until the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine($"Error: The file '{filePath}' was not found.");
}
catch (IOException ex)
{
Console.WriteLine($"An I/O error occurred: {ex.Message}");
}
}
}
Writing to a File
using System;
using System.IO;
public class FileWriter
{
public static void Main(string[] args)
{
string filePath = "output.txt";
try
{
// Using statement ensures the StreamWriter is disposed of properly.
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.WriteLine("This is the first line.");
sw.WriteLine("This is the second line.");
sw.Write("This is a third line without a newline.");
sw.WriteLine(" Appended!");
}
Console.WriteLine($"Successfully wrote to '{filePath}'.");
}
catch (IOException ex)
{
Console.WriteLine($"An I/O error occurred: {ex.Message}");
}
}
}
File and Directory Operations
using System;
using System.IO;
public class FileDirectoryOps
{
public static void Main(string[] args)
{
string dirPath = "MyNewDirectory";
string newFilePath = Path.Combine(dirPath, "my_document.txt");
try
{
// Create directory if it doesn't exist
Directory.CreateDirectory(dirPath);
Console.WriteLine($"Directory '{dirPath}' created or already exists.");
// Create and write to a file
File.WriteAllText(newFilePath, "Content of the new file.");
Console.WriteLine($"File '{newFilePath}' created.");
// Copy the file
string copiedFilePath = Path.Combine(dirPath, "my_document_copy.txt");
File.Copy(newFilePath, copiedFilePath, true); // Overwrite if exists
Console.WriteLine($"File copied to '{copiedFilePath}'.");
// Move the file
string movedFilePath = Path.Combine(dirPath, "renamed_document.txt");
File.Move(copiedFilePath, movedFilePath);
Console.WriteLine($"File moved to '{movedFilePath}'.");
// Read all lines from the moved file
string[] lines = File.ReadAllLines(movedFilePath);
Console.WriteLine($"Content of '{movedFilePath}':");
foreach (string line in lines)
{
Console.WriteLine($"- {line}");
}
// Delete the file and directory
File.Delete(movedFilePath);
Console.WriteLine($"File '{movedFilePath}' deleted.");
Directory.Delete(dirPath);
Console.WriteLine($"Directory '{dirPath}' deleted.");
}
catch (IOException ex)
{
Console.WriteLine($"An I/O error occurred: {ex.Message}");
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine($"Access denied: {ex.Message}");
}
}
}
Important Note: Always ensure you properly dispose of stream objects, typically by using the
using
statement. This guarantees that file handles are closed and resources are released, preventing potential issues like file locking.