C# / C# File I/O and Streams

Reading and Writing Text Files

In this tutorial, you'll learn how to read from and write to text files in C#. This includes understanding how to use StreamReader and StreamWriter classes.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores file handling and working with streams in C#.

1. Introduction

This tutorial is designed to introduce you to the process of reading from and writing to text files in C#. We will be using the StreamReader and StreamWriter classes in C# to accomplish this.

By the end of this tutorial, you will be able to:

  • Understand the StreamReader and StreamWriter classes
  • Read from text files
  • Write to text files

Prerequisites

  • Basic knowledge of C# programming language
  • A text editor such as Visual Studio or Notepad++
  • .NET Core installed on your machine

2. Step-by-Step Guide

In C#, we use the StreamReader class to read data from a text file, and StreamWriter to write data to a text file.

StreamReader Class

This class comes from the System.IO namespace and is used for reading characters from a byte stream in a particular encoding.

StreamWriter Class

This class is also part of the System.IO namespace and is used to write characters to a stream in a specific encoding.

3. Code Examples

Example 1: Reading from a Text File

Here's an example of how to read from a text file using StreamReader.

using System;
using System.IO;

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

Explanation

  • We start by creating a new instance of StreamReader, passing the name of the file we want to read from.
  • Then, we use a while loop to read each line of the file until there are no more lines to read.
  • Each line is then printed out to the console using Console.WriteLine().

Example 2: Writing to a Text File

Here's an example of how to write to a text file using StreamWriter.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writer = new StreamWriter("test.txt"))
        {
            writer.WriteLine("Hello, world!");
        }
    }
}

Explanation

  • We create a new instance of StreamWriter, passing the name of the file we want to write to.
  • We then use the WriteLine() method to write a line of text to the file.

4. Summary

In this tutorial, we've covered how to read from and write to text files in C# using the StreamReader and StreamWriter classes. We learned that the StreamReader class is used for reading data from a text file and the StreamWriter class is used for writing data to a text file.

For further learning, you could explore the other methods available in these classes, such as ReadToEnd() and Write().

5. Practice Exercises

Exercise 1: Write a program that reads a text file and counts the number of lines in the file.

Exercise 2: Write a program that writes the numbers 1 to 10 on separate lines in a text file.

Solutions

Solution to Exercise 1

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamReader reader = new StreamReader("test.txt"))
        {
            int lineCount = 0;
            while (reader.ReadLine() != null)
            {
                lineCount++;
            }
            Console.WriteLine("Number of lines: " + lineCount);
        }
    }
}

In this program, we read each line of the file and increment a counter for each line. The total count is then printed out.

Solution to Exercise 2

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writer = new StreamWriter("test.txt"))
        {
            for(int i=1; i<=10; i++)
            {
                writer.WriteLine(i);
            }
        }
    }
}

In this program, we use a for loop to write the numbers 1 to 10 on separate lines in the file.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help