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 file potato_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 to potato_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);
        }
    }
}