Reading and Writing Text Files in C# Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      18 mins read      Difficulty-Level: beginner

Reading and Writing Text Files in C#

Handling text files is a fundamental task in many software applications, and C# provides a robust set of tools in the System.IO namespace to facilitate these operations. Whether it's reading a configuration file, logging application data, or processing user input, understanding how to read from and write to text files efficiently is crucial. In this detailed guide, we'll dive into the essential aspects of reading from and writing to text files using C#.

1. The System.IO Namespace

To perform file operations in C#, you'll primarily work with classes from the System.IO namespace. This namespace includes numerous classes that provide functionalities for handling various types of file and data streams. For dealing with text files, we're mostly concerned with StreamReader and StreamWriter.

2. Writing Text to a File

Writing text to a file in C# can be done in a few different ways, but one of the most common methods is using the StreamWriter class.

2.1 Using StreamWriter

string path = @"example.txt";
using (StreamWriter sw = new StreamWriter(path))
{
    sw.WriteLine("Hello, World!");
    sw.WriteLine("This is a sample text file.");
}
  • Step-by-Step Explanation:

    • Specify the File Path: Define the path where the file will be created or overwritten. In this example, it's example.txt.
    • Create and Manage StreamWriter: The using statement ensures that the StreamWriter is properly disposed of after the block of code is executed, which is important for freeing up system resources.
    • Write Text: Use methods like WriteLine() to write text to the file.
  • Important Methods in StreamWriter:

    • Write(): Writes a string without a newline.
    • WriteLine(): Writes a string followed by a newline.
    • WriteLine(object value): Writes the string representation of an object followed by a newline.

2.2 Appending to a File

If you need to append text to an existing file instead of overwriting it, you can pass true as the second parameter to the StreamWriter constructor.

using (StreamWriter sw = new StreamWriter(path, true))
{
    sw.WriteLine("Appending new text to the file.");
}

3. Reading Text from a File

Reading text from a file can be handled using the StreamReader class, which provides functionalities to read from text files.

3.3 Using StreamReader

string path = @"example.txt";
using (StreamReader sr = new StreamReader(path))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
  • Step-by-Step Explanation:

    • Specify the File Path: Provide the path of the file you want to read.
    • Create and Manage StreamReader: Similar to StreamWriter, the using statement ensures proper disposal of StreamReader.
    • Read Text: Use ReadLine() to read text line by line. The loop continues until ReadLine() returns null, indicating the end of the file.
  • Important Methods in StreamReader:

    • Read(): Reads a single character as an integer.
    • ReadLine(): Reads a line of characters from the current stream and returns them as a string.
    • ReadToEnd(): Reads all characters from the current position to the end of the stream.

3.4 Handling Large Files

When dealing with large files, reading the entire file into memory at once can be inefficient or impractical. It's better to read the file in chunks or line by line, as demonstrated earlier.

4. Error Handling and Best Practices

Performing file operations can lead to exceptions, such as file not found, access denied, or I/O errors. It's crucial to handle these exceptions gracefully.

4.1 Exception Handling

string path = @"example.txt";
try
{
    using (StreamReader sr = new StreamReader(path))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}
catch (FileNotFoundException e)
{
    Console.WriteLine("File not found: " + e.Message);
}
catch (IOException e)
{
    Console.WriteLine("An I/O error occurred: " + e.Message);
}
catch (UnauthorizedAccessException e)
{
    Console.WriteLine("Access denied: " + e.Message);
}
finally
{
    Console.WriteLine("Operation complete.");
}

4.2 Best Practices

  • Use using Statements: Ensure that file streams are disposed of correctly to free up system resources.
  • Exception Handling: Implement try-catch-finally blocks to handle potential exceptions gracefully.
  • Check File Access: Always verify that the file exists and that your application has the necessary permissions to read from or write to the file.
  • Performance Considerations: For large files, read data in chunks or line by line to avoid excessive memory usage.

5. Additional Tips

5.1 Using File Static Methods

The File class provides static methods for reading and writing text files without explicitly creating StreamReader and StreamWriter instances.

string path = @"example.txt";
string[] lines = { "Hello", "World" };
File.WriteAllLines(path, lines);
  • Static Methods:
    • File.WriteAllText(): Writes text to a file, creating a new file if it doesn't exist or overwriting the file if it does.
    • File.WriteLines(): Writes a sequence of lines to a file, creating a new file if it doesn't exist or overwriting the file if it does.
    • File.ReadAllText(): Reads the contents of a text file into a string.
    • File.ReadAllLines(): Reads all lines of a text file into a string array.

5.2 Encoding Considerations

By default, StreamReader and StreamWriter use UTF-8 encoding. If you need to specify a different encoding, you can do so when creating the stream.

using (StreamWriter sw = new StreamWriter(path, false, Encoding.ASCII))
{
    sw.WriteLine("This text file uses ASCII encoding.");
}

Understanding the nuances of reading and writing text files in C# is essential for building robust and efficient applications. By leveraging the System.IO namespace and best practices, you can effectively manage file operations in your C# projects.


By following this guide, you should have a solid understanding of reading and writing text files in C#. Whether you're working on a simple console application or a complex enterprise solution, these foundational skills will serve you well. Happy coding!

Examples, Set Route, and Run the Application: Step-by-Step Guide for Reading and Writing Text Files in C#

Introduction

Working with files is a fundamental task in software development, and understanding how to read from and write to text files is essential. This step-by-step guide will provide a beginner-friendly approach to reading from and writing to text files in C#. We'll walk through setting up your development environment, creating a simple console application, and executing code that performs read/write operations on text files.

Setting Up Your Development Environment

Before we dive into reading and writing text files, let’s make sure we have the necessary tools ready.

  1. Install Visual Studio:
    • Download and install Visual Studio from the official website: Visual Studio.
    • During installation, make sure to select the ".NET desktop development" workload.

Creating a Console Application

  1. Open Visual Studio:

    • Launch Visual Studio and select "Create a new project".
  2. Select Console App Project:

    • Choose "Console App" under C# project types.
    • Click "Next".
  3. Configure Your Project:

    • Enter the project name (e.g., FileReadWrite).
    • Choose the location and solution name.
    • Click "Create".
  4. Solution Explorer:

    • You should see a Program.cs file in the Solution Explorer. This is where we will write our code.

Writing to a Text File

To write data to a text file, we will use the System.IO namespace, which includes classes like StreamWriter.

  1. Using Statements:

    • At the top of Program.cs, add the following using statement:
      using System.IO;
      
  2. Write to File Code:

    • Replace the existing code in Program.cs with the following:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main(string[] args)
          {
              string filePath = "example.txt";
      
              // Writing text to the file
              using (StreamWriter writer = new StreamWriter(filePath))
              {
                  writer.WriteLine("Hello, World!");
                  writer.WriteLine("Welcome to File Read/Write in C#.");
              }
      
              Console.WriteLine("Data written to file successfully.");
          }
      }
      
  3. Explanation:

    • We specify a file path (example.txt) where the data will be written.
    • StreamWriter is used to write text to the file. It is wrapped in a using statement to ensure proper disposal of the writer.
    • WriteLine methods write lines of text to the file.
  4. Running the Application:

    • Press F5 or click on the "Start" button to run the application.
    • After running, check the project directory for the example.txt file. It should contain the lines "Hello, World!" and "Welcome to File Read/Write in C#."

Reading from a Text File

To read data from a text file, we will use the StreamReader class, also found in the System.IO namespace.

  1. Read from File Code:

    • Modify the Main method in Program.cs to include reading from the file:
      using System;
      using System.IO;
      
      class Program
      {
          static void Main(string[] args)
          {
              string filePath = "example.txt";
      
              // Writing text to the file
              using (StreamWriter writer = new StreamWriter(filePath))
              {
                  writer.WriteLine("Hello, World!");
                  writer.WriteLine("Welcome to File Read/Write in C#.");
              }
      
              Console.WriteLine("Data written to file successfully.");
      
              // Reading text from the file
              using (StreamReader reader = new StreamReader(filePath))
              {
                  string line;
                  while ((line = reader.ReadLine()) != null)
                  {
                      Console.WriteLine(line);
                  }
              }
      
              Console.WriteLine("Data read from file successfully.");
          }
      }
      
  2. Explanation:

    • We use StreamReader to read the file line by line.
    • The ReadLine method reads a line of characters from the file until the end of the line is reached.
    • The while loop continues as long as ReadLine does not return null, indicating the end of the file.
  3. Running the Application:

    • Run the application again by pressing F5.
    • The console should display the contents of example.txt, confirming that the data was successfully read from the file.

Data Flow Step-by-Step

  1. Application Launch:

    • The application starts and begins execution of the Main method.
  2. Writing Data:

    • A StreamWriter object is created and used to write two lines of text to example.txt.
    • The StreamWriter is disposed of automatically due to the using statement.
  3. Reading Data:

    • A StreamReader object is created to read the contents of example.txt.
    • Lines are read until the end of the file, and each line is printed to the console.
    • The StreamReader is disposed of automatically due to the using statement.
  4. Completion:

    • The application ends, and the console displays messages confirming successful write and read operations.

Conclusion

Reading from and writing to text files in C# is a straightforward process that can be accomplished using the System.IO namespace. In this guide, we created a console application that writes data to a text file and then reads it back. By following these steps, you now have a solid foundation for handling file I/O operations in C#. As you continue to develop your C# skills, exploring more advanced file operations will enhance your ability to manipulate various types of data files.

Certainly! Here are the top 10 questions and answers related to reading and writing text files in C#. These answers provide a comprehensive overview of common file operations using C#.

1. How can I read a text file in C#?

Answer:
To read a text file in C#, you can use the System.IO.File.ReadAllText method to read the entire file into a string, or System.IO.File.ReadLines for reading the file line by line. Here's how you can use each method:

  • Using File.ReadAllText:

    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            try
            {
                string filePath = "example.txt";
                string content = File.ReadAllText(filePath);
                Console.WriteLine(content);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
    
  • Using File.ReadLines:

    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            try
            {
                string filePath = "example.txt";
                foreach (string line in File.ReadLines(filePath))
                {
                    Console.WriteLine(line);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
    

2. How can I write a string to a text file in C#?

Answer:
You can write a string to a text file using System.IO.File.WriteAllText or append text using File.AppendAllText. Here are examples of both:

  • Writing to a file (overwriting existing content):

    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            try
            {
                string filePath = "example.txt";
                string content = "Hello, World!";
                File.WriteAllText(filePath, content);
                Console.WriteLine("Text written to file successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
    
  • Appending to a file:

    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            try
            {
                string filePath = "example.txt";
                string contentToAppend = "\nThis is appended text.";
                File.AppendAllText(filePath, contentToAppend);
                Console.WriteLine("Text appended to file successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
    

3. How do I handle exceptions when reading and writing files in C#?

Answer:
When performing file operations, it is essential to handle exceptions to prevent your application from crashing unexpectedly. Common exceptions include FileNotFoundException, UnauthorizedAccessException, and IOException. Here's an example that handles various exceptions:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        string content = "Hello, World!";

        try
        {
            File.WriteAllText(filePath, content);
            Console.WriteLine("Text written to file successfully.");
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine($"Access denied: {ex.Message}");
        }
        catch (DirectoryNotFoundException ex)
        {
            Console.WriteLine($"Directory not found: {ex.Message}");
        }
        catch (IOException ex)
        {
            Console.WriteLine($"IO error: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}

4. How can I read a file one line at a time in C#?

Answer:
You can read a file one line at a time using System.IO.File.ReadLines, which is memory efficient since it reads one line at a time and doesn’t load the entire file into memory. Here’s an example:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        try
        {
            foreach (string line in File.ReadLines(filePath))
            {
                Console.WriteLine(line);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

5. How can I check if a file exists before trying to read it in C#?

Answer:
To avoid FileNotFoundException, you can check if a file exists using System.IO.File.Exists before attempting to read it. Here’s how:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

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

6. How do I read binary files in C#?

Answer:
While the question is about text files, it’s worth mentioning that binary files can be read similarly using FileStream along with a BinaryReader. Here is an example:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.bin";

        try
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (BinaryReader br = new BinaryReader(fs))
            {
                int number = br.ReadInt32();
                Console.WriteLine($"Read integer: {number}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

7. How can I write to a file using FileStream in C#?

Answer:
Similar to reading, you can write to a file using FileStream and BinaryWriter for binary data. Here’s an example for writing:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.bin";
        int numberToWrite = 12345;

        try
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                bw.Write(numberToWrite);
                Console.WriteLine($"Written integer: {numberToWrite}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

8. How can I read from and write to a file asynchronously in C#?

Answer:
For efficient handling of large files or to keep your UI responsive, you can use asynchronous file operations. C# provides methods like File.ReadAllTextAsync, File.WriteAllTextAsync, and StreamReader/StreamWriter with ReadAsync/WriteAsync methods. Here’s how you can use StreamReader and StreamWriter:

  • Reading asynchronously:

    using System;
    using System.IO;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main()
        {
            string filePath = "example.txt";
    
            try
            {
                using (StreamReader sr = new StreamReader(filePath))
                {
                    string content = await sr.ReadToEndAsync();
                    Console.WriteLine(content);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
    
  • Writing asynchronously:

    using System;
    using System.IO;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main()
        {
            string filePath = "example.txt";
            string content = "Hello, World!";
    
            try
            {
                using (StreamWriter sw = new StreamWriter(filePath, false))
                {
                    await sw.WriteAsync(content);
                    Console.WriteLine("Text written to file successfully.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
    

9. How can I perform buffered I/O operations when reading and writing files in C#?

Answer:
Buffered I/O operations are typically handled automatically when using StreamReader, StreamWriter, FileStream, and other I/O classes in C#. Buffered I/O improves performance by reducing the number of I/O operations, as data is read from or written to an in-memory buffer.

Here’s an example using StreamReader with buffering:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        try
        {
            using (StreamReader sr = new StreamReader(filePath))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

10. How can I append multiple strings to a file in C#?

Answer:
To append multiple strings to a file, you can use File.AppendAllLines or repeatedly call File.AppendAllText. Here’s an example using File.AppendAllLines:

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        List<string> linesToAppend = new List<string>
        {
            "Line 1",
            "Line 2",
            "Line 3"
        };

        try
        {
            File.AppendAllLines(filePath, linesToAppend);
            Console.WriteLine("Lines appended to file successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

These examples cover common scenarios involving reading and writing text files in C#. Understanding these concepts will help you efficiently manage file operations in your applications.