πŸ”Ÿ C# File and Exception Handling
Estimated reading: 3 minutes 265 views

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, and File classes
  • 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:

ClassDescription
FileProvides static methods for file operations like Create, Delete, Exists, etc.
StreamWriterWrites characters to a stream (commonly used for text files).
StreamReaderReads characters from a stream.
FileStreamUsed for both reading and writing to files at a lower level (binary or text).
BinaryReader / BinaryWriterUsed 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:

  • WriteAllText creates 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:

  • ReadAllText reads 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:

  • AppendAllText adds 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 StreamReader inside a using block 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: true keeps 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

MethodUse CaseSynchronousReads AllAppends
File.ReadAllText()Small text filesβœ”οΈβœ”οΈ
File.AppendAllText()Add to end of a text fileβœ”οΈβœ”οΈ
StreamReaderLine-by-line processingβœ”οΈ
StreamWriterLine-by-line writingβœ”οΈβœ”οΈ/
FileStreamLow-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 File for simple file operations
  • StreamReader / StreamWriter for 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 :
Share

πŸ’Ύ C# File I/O / C# File Handling

Or Copy Link

CONTENTS
Scroll to Top