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.
Section overview
5 resourcesExplores 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article