C# / C# File I/O and Streams

Working with FileStream and StreamReader

Here, we'll delve deeper into the FileStream and StreamReader classes. You'll learn how to use them to handle larger files that don't fit into memory.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores file handling and working with streams in C#.

Introduction

In this tutorial, we will explore FileStream and StreamReader classes in .NET. These classes are used for reading from and writing to files. We will specifically learn how to handle larger files that don't fit into memory.

By the end of this tutorial, you will be able to:
* Understand the basics of FileStream and StreamReader classes
* Use FileStream and StreamReader to read and write data
* Handle large files efficiently

Prerequisites:
You should have a basic understanding of C# and .NET framework.

Step-by-Step Guide

FileStream and StreamReader are part of the System.IO namespace in .NET. FileStream is used to read from and write to any location in a file. StreamReader is used for reading characters from a byte stream.

FileStream:
FileStream allows you to move forwards and backwards in a file. It can be used with Read, Write, CopyTo, and other methods.

StreamReader:
StreamReader is designed to read from a byte stream. It can handle character encoding automatically and can read from a binary stream.

Best Practices:
* Always close your streams. This can be done manually with the Close method, or automatically with the using keyword.
* Handle exceptions. File operations can fail for many reasons, so always put your code inside a try/catch block.

Code Examples

Example 1: Reading a file with FileStream and StreamReader

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.Read))
        {
            using (StreamReader sr = new StreamReader(fs))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
    }
}

In this example, we first create a FileStream fs to open the file test.txt. Then, we create a StreamReader sr to read from this FileStream. The ReadLine method is used to read the file line by line. If the line is not null, we print it to the console.

Example 2: Writing to a file with FileStream

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (FileStream fs = new FileStream("test.txt", FileMode.Create, FileAccess.Write))
        {
            byte[] info = new System.Text.UTF8Encoding(true).GetBytes("This is some text in the file.");
            fs.Write(info, 0, info.Length);
        }
    }
}

In this example, we first create a FileStream fs to create and write to the file test.txt. We then write the byte array info to the file using the Write method.

Summary

In this tutorial, we have learned about the FileStream and StreamReader classes in .NET. We've seen how to use these classes to read from and write to files, and how to handle large files that don't fit into memory.

You can continue learning by exploring other classes in the System.IO namespace, such as StreamWriter and MemoryStream.

Practice Exercises

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

Exercise 2:
Create a program that writes an array of strings to a text file, with each string on a new line.

Exercise 3:
Create a program that reads a large text file and writes its contents to another file in reverse order (last line first).

Tips for further practice:
Try to handle different types of data, such as binary data or encoded text. Try to handle exceptions and errors that may occur during file operations.

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

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

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

File Size Checker

Check the size of uploaded files.

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