File IO with Streams - potatoscript/csharp GitHub Wiki
π File I/O with Streams in C# π
π₯ What is File I/O?
File I/O (Input/Output) allows your C# program to read data from a file (input) or write data to a file (output).
β‘οΈ Input β Taking data from a file and loading it into the program.
β¬
οΈ Output β Writing data from the program to a file.
Think of it as reading a recipe from a book π or writing your favorite potato recipe into your secret cookbook. ππ΄
π― Why Use Streams?
A stream is like a pipeline that lets data flow between a file and your program. Imagine a stream of water carrying information back and forth. π§π
β
Streams allow data to move smoothly between the source (file) and destination (program).
β
You can read, write, or manipulate data using streams.
π₯ Types of Streams in C#
C# provides different types of streams for different tasks:
π Stream Type | π Purpose |
---|---|
FileStream |
Read and write binary data to/from files. |
StreamReader |
Read text data from a file. |
StreamWriter |
Write text data to a file. |
MemoryStream |
Store data in memory temporarily. |
π Letβs Explore with a Story!
π₯ PotatoScript wants to save her favorite potato recipes in a file and read them later. But this time, she wants to use streams to do the job efficiently! π²π
π Step 1: Using FileStream for Basic File Operations
FileStream
is used for reading and writing binary data (such as images, videos, and other raw data) or text data.
π FileStream β Basic Syntax:
using System;
using System.IO;
class Program
{
static void Main()
{
// Create a FileStream to write data
using (FileStream fs = new FileStream("potato_recipes.txt", FileMode.Create))
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("π₯ Potato Fries\nπ₯ Mashed Potatoes\nπ₯ Potato Salad");
fs.Write(data, 0, data.Length);
Console.WriteLine("Recipes have been written to the file using FileStream! π");
}
}
}
π§ Explanation:
FileStream
opens or creates the filepotato_recipes.txt
.fs.Write()
writes binary data to the file.Encoding.UTF8.GetBytes()
converts the text to bytes before writing.using
ensures that the stream is properly closed after the operation.
π Output:
Recipes have been written to the file using FileStream! π
π Reading Data Using FileStream:
using System;
using System.IO;
class Program
{
static void Main()
{
// Create a FileStream to read data
using (FileStream fs = new FileStream("potato_recipes.txt", FileMode.Open))
{
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
string content = System.Text.Encoding.UTF8.GetString(data);
Console.WriteLine("Here are the recipes:\n" + content);
}
}
}
π Output:
Here are the recipes:
π₯ Potato Fries
π₯ Mashed Potatoes
π₯ Potato Salad
π Step 2: Reading and Writing with StreamReader and StreamWriter
If youβre working with text files, StreamReader
and StreamWriter
make it easier.
βοΈ Writing to a File with StreamWriter:
using System;
using System.IO;
class Program
{
static void Main()
{
// Write to the file using StreamWriter
using (StreamWriter writer = new StreamWriter("potato_notes.txt"))
{
writer.WriteLine("π₯ Remember to buy more potatoes!");
writer.WriteLine("π₯ Try a new potato salad recipe.");
Console.WriteLine("Notes have been written successfully! π");
}
}
}
π§ Explanation:
StreamWriter
writes text data topotato_notes.txt
.writer.WriteLine()
writes one line at a time.using
ensures the file is closed after writing.
π Output:
Notes have been written successfully! π
π Reading a File with StreamReader:
using System;
using System.IO;
class Program
{
static void Main()
{
// Read data from the file using StreamReader
using (StreamReader reader = new StreamReader("potato_notes.txt"))
{
string note;
while ((note = reader.ReadLine()) != null)
{
Console.WriteLine("π " + note);
}
}
}
}
π Output:
π π₯ Remember to buy more potatoes!
π π₯ Try a new potato salad recipe.
π Step 3: Using MemoryStream for Temporary Data Storage
MemoryStream
is used to store data temporarily in memory instead of writing to a file.
π Writing to MemoryStream:
using System;
using System.IO;
class Program
{
static void Main()
{
// Create a MemoryStream
using (MemoryStream ms = new MemoryStream())
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("π₯ Data stored in memory!");
ms.Write(data, 0, data.Length);
// Read the data back
ms.Position = 0; // Reset the position to read from the beginning
byte[] readData = new byte[ms.Length];
ms.Read(readData, 0, readData.Length);
string content = System.Text.Encoding.UTF8.GetString(readData);
Console.WriteLine("Data from memory: " + content);
}
}
}
π Output:
Data from memory: π₯ Data stored in memory!
π Step 4: Appending Data Using StreamWriter
To add more data without deleting existing content, use StreamWriter
in append mode.
using System;
using System.IO;
class Program
{
static void Main()
{
// Append data to the file
using (StreamWriter writer = new StreamWriter("potato_notes.txt", true))
{
writer.WriteLine("π₯ Don't forget the garlic for mashed potatoes!");
Console.WriteLine("New note added! π");
}
}
}
π Output:
New note added! π
Now potato_notes.txt
contains:
π₯ Remember to buy more potatoes!
π₯ Try a new potato salad recipe.
π₯ Don't forget the garlic for mashed potatoes!
π Step 5: Advanced File I/O with BufferedStream
BufferedStream
improves read/write performance by reducing the number of I/O operations.
π Writing Data Using BufferedStream:
using System;
using System.IO;
class Program
{
static void Main()
{
using (FileStream fs = new FileStream("potato_data.txt", FileMode.Create))
using (BufferedStream bs = new BufferedStream(fs))
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("π₯ Buffered data for faster I/O!");
bs.Write(data, 0, data.Length);
Console.WriteLine("Buffered data written successfully! π");
}
}
}
π Reading Data Using BufferedStream:
using System;
using System.IO;
class Program
{
static void Main()
{
using (FileStream fs = new FileStream("potato_data.txt", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
{
byte[] data = new byte[fs.Length];
bs.Read(data, 0, data.Length);
string content = System.Text.Encoding.UTF8.GetString(data);
Console.WriteLine("Buffered data read successfully: " + content);
}
}
}