πΎ C# File I/O / C# File Handling β A Complete Guide for Beginners
π§² Introduction β Why Learn C# File Handling?
Modern software often needs to read, write, and manipulate filesβwhether it’s processing user data, generating logs, or storing persistent information. File handling is a fundamental feature in C# programming that empowers developers to interact with the file system efficiently.
π In this guide, you’ll learn:
- How to perform basic file operations (create, read, write, delete)
- How to use StreamReader,StreamWriter, andFileclasses
- Error handling during file I/O
- Best practices and performance tips
π Core Concepts β Understanding File I/O in C#
C# provides multiple classes and namespaces for file handling under the System.IO namespace. Key classes include:
| Class | Description | 
|---|---|
| File | Provides static methods for file operations like Create, Delete, Exists, etc. | 
| StreamWriter | Writes characters to a stream (commonly used for text files). | 
| StreamReader | Reads characters from a stream. | 
| FileStream | Used for both reading and writing to files at a lower level (binary or text). | 
| BinaryReader/BinaryWriter | Used for reading/writing primitive data types in binary form. | 
π» Code Examples β With Step-by-Step Explanations
β 1. Writing to a Text File
using System.IO;
File.WriteAllText("sample.txt", "Hello, World!");
π Explanation:
- WriteAllTextcreates a file if it doesn’t exist or overwrites it if it does.
- Writes the specified string content into the file.
β 2. Reading a Text File
using System.IO;
string content = File.ReadAllText("sample.txt");
Console.WriteLine(content);
π Explanation:
- ReadAllTextreads the entire content of a text file and returns it as a string.
β 3. Appending to a Text File
File.AppendAllText("sample.txt", "\nWelcome to C# File I/O!");
π Explanation:
- AppendAllTextadds content to the end of the existing file.
β 4. Reading Line-by-Line Using StreamReader
using (StreamReader reader = new StreamReader("sample.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
π Explanation:
- Uses StreamReaderinside ausingblock for safe disposal.
- Reads each line until EOF (null).
β 5. Writing Line-by-Line Using StreamWriter
using (StreamWriter writer = new StreamWriter("log.txt", append: true))
{
    writer.WriteLine("Log Entry at " + DateTime.Now);
}
π Explanation:
- append: truekeeps existing data intact.
- Logs timestamped data line-by-line.
π‘ Best Practices & Tips
π Best Practice: Always close streams using using blocks to avoid resource leaks.
π‘ Tip: Prefer File.ReadAllText() or File.WriteAllText() for small, simple files.
β οΈ Pitfall: Avoid reading huge files entirely into memory. Use StreamReader for large files.
π Functional Comparison Table
| Method | Use Case | Synchronous | Reads All | Appends | 
|---|---|---|---|---|
| File.ReadAllText() | Small text files | βοΈ | βοΈ | β | 
| File.AppendAllText() | Add to end of a text file | βοΈ | β | βοΈ | 
| StreamReader | Line-by-line processing | βοΈ | β | β | 
| StreamWriter | Line-by-line writing | βοΈ | β | βοΈ/β | 
| FileStream | Low-level binary/text I/O | βοΈ | β | βοΈ/β | 
π οΈ Real-World Use Cases
- β
 Logging systems (StreamWriter)
- β
 Configuration loaders (File.ReadAllText)
- β
 File migration tools (FileStream)
- β Import/export CSV, TXT, JSON
π Summary β Recap & Next Steps
Efficient file handling is essential in all softwareβfrom desktop applications to web APIs and services.
π Key Takeaways:
- Use Filefor simple file operations
- StreamReader/- StreamWriterfor line-based access
- Always handle exceptions for robust code
βοΈ Explore next: Binary file access, file I/O performance optimization, directory traversal using Directory class.
β FAQ Section
β How do I check if a file exists in C#?
β
 Use File.Exists(path). Returns true if the file exists.
β How to delete a file in C#?
β
 Use File.Delete(path) to remove a file.
β How do I read a file line-by-line efficiently?
β
 Use StreamReader.ReadLine() in a while loop for large files.
β What’s the difference between File and FileStream?
β
 File is for high-level operations; FileStream gives low-level control (binary mode).
β Can I read/write binary data using File classes?
β
 Yes, use BinaryReader and BinaryWriter for reading/writing primitives in binary format.
β What happens if the file doesn’t exist during reading?
β
 An exception is thrown. Always check with File.Exists() before reading.
Share Now :
