C# File Read and Write: Complete Guide with Examples and Best Practices

C# File Read and Write: Complete Guide with Examples and Best Practices

File read/write in C# refers to operations that allow reading data from files and writing data to files using the System.IO namespace.

File handling is a fundamental part of many applications, especially when working with logs, configuration files, reports, or data storage. C# provides multiple ways to perform file operations, including the File class for simple tasks and StreamReader / StreamWriter for more controlled reading and writing. These tools help developers interact with the file system efficiently while managing resources properly.

When is File Read/Write Needed?

Use file operations when:

• Saving application data locally
• Reading configuration files
• Logging application events
• Exporting reports or data
• Processing external text files

How to Use File Read/Write?

Reading a File (Simple Approach)

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string content = File.ReadAllText("data.txt");
        Console.WriteLine(content);
    }
}

Writing to a File

using System;
using System.IO;

class Program
{
    static void Main()
    {
        File.WriteAllText("output.txt", "Hello C# File Handling");
        Console.WriteLine("File written successfully");
    }
}

Using StreamReader

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamReader reader = new StreamReader("data.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

Using StreamWriter

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writer = new StreamWriter("log.txt"))
        {
            writer.WriteLine("Application started");
            writer.WriteLine("Processing data...");
        }

        Console.WriteLine("Log written successfully");
    }
}

File Handling Methods Comparison

Method Usage Best For
File.ReadAllText Reads entire file into memory Small files
File.WriteAllText Writes full content at once Simple file writing
StreamReader Reads line by line Large files
StreamWriter Writes line by line Logs and continuous writing

Advantages and Disadvantages

Advantages Disadvantages
Easy to store persistent data File operations are slower than memory
Useful for logging and configuration Requires proper error handling
Supports large data processing Risk of file corruption if not handled correctly
Multiple built-in APIs available Needs careful resource management

Similar and Alternative Options

Option Description When to Use
Database storage Stores structured data Large or relational data
Memory storage Temporary runtime storage Fast processing needs
Serialization Convert objects to file format Saving complex objects
Cloud storage Remote file storage Scalable applications

Common Mistakes

• Forgetting to close streams (not using using statement)
• Reading large files with ReadAllText causing memory issues
• Not handling file not found exceptions
• Overwriting files unintentionally with WriteAllText
• Using incorrect file paths
• Ignoring encoding issues when reading/writing text

Contents related to 'C# File Read and Write: Complete Guide with Examples and Best Practices'

C# First vs FirstOrDefault: Differences, Usage, and Examples in LINQ
C# First vs FirstOrDefault: Differences, Usage, and Examples in LINQ
C# JSON Serialization: Complete Guide with Examples and Best Practices
C# JSON Serialization: Complete Guide with Examples and Best Practices