*
Previous LINQ in C# Exception Handling and Logging in C# Next

📂 File I/O in C#

File I/O in C#

In C#, File I/O (Input/Output) refers to the process of reading from and writing to files, which is handled by the System.IO namespace. C# represents a file as a stream of bytes, and the System.IO classes provide different ways to interact with these streams.

Key Classes in System.IO

  • File: Provides static methods for creating, copying, deleting, and moving files.
  • FileStream: Allows synchronous and asynchronous reading and writing of bytes to and from a file.
  • StreamWriter and StreamReader: Used for writing and reading text-based data from files.

Types of Opening Files using FileMode

When you open a file, you specify a FileMode from the System.IO enumeration to control how the operating system handles the file.

FileMode Member Description
Create Creates a new file. Overwrites if it exists.
CreateNew Creates a new file. Throws an exception if it exists.
Open Opens an existing file.
OpenOrCreate Opens an existing file or creates a new one if it doesn’t exist.
Append Opens a file and seeks to the end. Creates the file if it doesn’t exist.
Truncate Opens an existing file and sets its size to zero.

📂 File I/O in C#

File I/O (Input/Output) in C# is handled using the System.IO namespace. It allows you to create, read, write, append, and manipulate files and directories efficiently.

📁 Types of File Access

  • FileStream: Low-level access to file bytes.
  • StreamReader / StreamWriter: For reading/writing text files.
  • File Class: Static methods for quick file operations.
  • BinaryReader / BinaryWriter: For binary data.

📝 Create a File

using System.IO;

File.WriteAllText("example.txt", "Hello, Shivshanker!");

📖 Read a File

string content = File.ReadAllText("example.txt");
Console.WriteLine(content);

➕ Append to a File

File.AppendAllText("example.txt", "\nWelcome to File I/O in C#.");

🔍 Find and Replace Text

string text = File.ReadAllText("example.txt");
text = text.Replace("Shivshanker", "Developer");
File.WriteAllText("example.txt", text);

🔗 Merge Two Files

string file1 = File.ReadAllText("file1.txt");
string file2 = File.ReadAllText("file2.txt");

File.WriteAllText("merged.txt", file1 + "\n" + file2);

C# File I/O Examples

1. Create and Write to a File

File.WriteAllText writes a string to a new file, overwriting existing content.

using System;
using System.IO;

class FileOperations
{
static void Main()
{
string path = "example.txt";
string content = "This is the first line.\nThis is the second line.";


    try
    {
        File.WriteAllText(path, content);
        Console.WriteLine("File created and written successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}


} 

2. Read from a File

File.ReadAllText reads the entire content of a text file into a string.

using System;
using System.IO;

class FileOperations
{
static void Main()
{
string path = "example.txt";


    try
    {
        if (File.Exists(path))
        {
            string content = File.ReadAllText(path);
            Console.WriteLine("File content:");
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine("File not found.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}

} 

3. Append to a File

File.AppendAllText appends a string to a file, creating it if it doesn’t exist.

using System;
using System.IO;

class FileOperations
{
static void Main()
{
string path = "example.txt";
string contentToAppend = "\nThis is a new appended line.";

    try
    {
        File.AppendAllText(path, contentToAppend);
        Console.WriteLine("Content appended to file successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}

} 

4. Find and Replace Text in a File

Finding and replacing text often involves reading the file into memory, modifying the string, and writing it back.

using System;
using System.IO;

class FileOperations
{
static void Main()
{
string path = "example.txt";

    try
    {
        if (File.Exists(path))
        {
            string content = File.ReadAllText(path);
            content = content.Replace("second line", "replaced line");
            File.WriteAllText(path, content);
            Console.WriteLine("Content replaced successfully.");
        }
        else
        {
            Console.WriteLine("File not found.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}

} 

5. Merge Two Files

Merging files can be done by reading content from source files and writing it to a destination file using File.AppendAllLines to merge line by line.

using System;
using System.IO;

class FileOperations
{
static void Main()
{
string file1Path = "file1.txt";
string file2Path = "file2.txt";
string mergedFilePath = "merged.txt";

    // Create example files
    File.WriteAllText(file1Path, "Content from File 1.");
    File.WriteAllText(file2Path, "Content from File 2.");

    try
    {
        // Read all lines from the source files
        string[] file1Content = File.ReadAllLines(file1Path);
        string[] file2Content = File.ReadAllLines(file2Path);

        // Merge the content into the new file
        File.WriteAllLines(mergedFilePath, file1Content);
        File.AppendAllLines(mergedFilePath, file2Content);

        Console.WriteLine("Files merged successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
  }
} 

Example: Reading and Replacing Line-by-Line

This example demonstrates how to find and replace specific text only on the lines where it occurs. It is memory-efficient, as it only holds one line in memory at a time.

Steps

  1. Create a source file. For this example, you'll need a text file named input.txt.
  2. Create a console application.
  3. Use the code below. This program:
    • Reads the file line by line using StreamReader.
    • Creates a temporary file for the new content.
    • Iterates through each line, performs the replacement if the search text is found, and writes the modified or original line to the temporary file.
    • Replaces the original file with the temporary file.

Program.cs

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string inputPath = "input.txt";
        string outputPath = "output.tmp"; // Temporary file
        string findText = "old text";
        string replaceText = "new text";

        // Create a dummy input file for demonstration
        File.WriteAllText(inputPath, "This line has old text that should be replaced.\n" +
                                       "This line should remain unchanged.\n" +
                                       "Another line with old text to be replaced.");

        try
        {
            using (var reader = new StreamReader(inputPath))
            using (var writer = new StreamWriter(outputPath))
            {
                string? line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Contains(findText))
                    {
                        // Replace the content within the current line only
                        string modifiedLine = line.Replace(findText, replaceText);
                        writer.WriteLine(modifiedLine);
                    }
                    else
                    {
                        // Write the original line unchanged
                        writer.WriteLine(line);
                    }
                }
            }

            // Replace the original file with the new one
            File.Delete(inputPath);
            File.Move(outputPath, inputPath);
            
            Console.WriteLine("File processing complete. Check input.txt for the changes.");

            // Display the final content of the file
            Console.WriteLine("\n--- Final file content ---");
            Console.WriteLine(File.ReadAllText(inputPath));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Summary

  • The System.IO namespace provides powerful classes for file manipulation.
  • Use FileMode to control how files are opened or created.
  • Always handle exceptions when working with file I/O to avoid runtime errors.
  • Use File.ReadAllText, File.WriteAllText, and File.AppendAllText for simple text operations.

✅ Best Practices

  • Use using blocks for StreamReader/StreamWriter to ensure proper disposal.
  • Always check if a file exists using File.Exists() before reading or deleting.
  • Handle exceptions with try-catch to avoid crashes.
  • Use Path.Combine() for cross-platform file paths.
  • Avoid hardcoding paths—use configuration or environment variables.

📌 When to Use

  • For logging, configuration, or data persistence.
  • To process text files, reports, or user-generated content.
  • In desktop or backend applications that interact with the file system.

🚫 When Not to Use

  • In web apps where file access is restricted or better handled via cloud storage.
  • For large-scale data—consider databases or streaming APIs.
  • When concurrency is critical—use thread-safe mechanisms.

⚠️ Precautions

  • Ensure proper permissions before accessing files.
  • Validate user input to avoid path traversal attacks.
  • Close file handles to prevent resource leaks.
  • Use locks or async I/O for concurrent access.

🎯 Advantages

  • Simple API: Easy to use for basic tasks.
  • Flexible: Supports text, binary, and stream-based access.
  • Efficient: Good for small to medium-sized data operations.
  • Cross-platform: Works on Windows, Linux, and macOS.

📝 Conclusion

File I/O in C# is a powerful tool for managing data on disk. Whether you're creating logs, reading configs, or merging reports, mastering these operations will make your applications more robust and versatile.

Back to Index
Previous LINQ in C# Exception Handling and Logging in C# Next
*
*