πŸ”Ÿ C# File and Exception Handling
Estimated reading: 3 minutes 28 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

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

Or Copy Link

CONTENTS
Scroll to Top