Reading and Writing Files - potatoscript/csharp GitHub Wiki

πŸ“š Reading and Writing Files in C# πŸ“š


πŸ₯” What is File Handling?

In C#, file handling lets you work with files stored on your computer. You can:

βœ… Read files – Get data from a file.
βœ… Write to files – Save data to a file.
βœ… Append data – Add more information without deleting what’s already there.

Imagine a magic notebook πŸ“” where you can read what’s written inside, write new things, or add more notes later without erasing anything! ✏️✨


🎯 Why Do We Need File Handling?

  1. Save Information Permanently – Unlike variables that are lost when the program ends, data stored in files stays there.
  2. Load and Process Large Data – Read large amounts of information from a file and process it.
  3. Store User Preferences – Save user settings that can be reloaded the next time the app runs.
  4. Data Exchange – Share information between different applications.

πŸ“„ Basic Concepts of File Handling

There are three main classes in the System.IO namespace that help you handle files:

  1. File – Provides methods to perform file operations.
  2. StreamReader – Reads data from a file.
  3. StreamWriter – Writes data to a file.

🎁 Let’s Explore with a Story!

πŸ₯” Meet PotatoScript! PotatoScript wants to write a list of ingredients for her favorite potato recipes and read them later. 🍟


πŸ“ Step 1: Writing to a File

To write data to a file, use the StreamWriter class.

πŸ“„ Basic Structure for Writing:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Create a file and write data to it
        using (StreamWriter writer = new StreamWriter("potato_recipes.txt"))
        {
            writer.WriteLine("πŸ₯” Potato Fries");
            writer.WriteLine("πŸ₯” Mashed Potatoes");
            writer.WriteLine("πŸ₯” Potato Salad");
            Console.WriteLine("Recipes have been written to the file! πŸ“„");
        }
    }
}

🧠 Explanation:

  • StreamWriter – Writes data to the file potato_recipes.txt.
  • writer.WriteLine() – Writes one line at a time.
  • using – Ensures the file is closed properly after writing.

🎁 Output:

Recipes have been written to the file! πŸ“„

A file named potato_recipes.txt is created with the following content:

πŸ₯” Potato Fries
πŸ₯” Mashed Potatoes
πŸ₯” Potato Salad

πŸ“ Step 2: Reading from a File

To read data from a file, use the StreamReader class.

πŸ“„ Basic Structure for Reading:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Read data from the file
        using (StreamReader reader = new StreamReader("potato_recipes.txt"))
        {
            string recipe;
            while ((recipe = reader.ReadLine()) != null)
            {
                Console.WriteLine("🍴 " + recipe);
            }
        }
    }
}

🧠 Explanation:

  • StreamReader – Reads data from the file potato_recipes.txt.
  • reader.ReadLine() – Reads one line at a time.
  • The while loop continues until there are no more lines to read.

🎁 Output:

🍴 πŸ₯” Potato Fries
🍴 πŸ₯” Mashed Potatoes
🍴 πŸ₯” Potato Salad

✨ Step 3: Appending Data to a File

To add more data without deleting what’s already there, use StreamWriter with the append parameter set to true.

πŸ“„ Basic Structure for Appending:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Append data to the file
        using (StreamWriter writer = new StreamWriter("potato_recipes.txt", true))
        {
            writer.WriteLine("πŸ₯” Baked Potatoes");
            writer.WriteLine("πŸ₯” Potato Soup");
            Console.WriteLine("More recipes have been added! 🍲");
        }
    }
}

🧠 Explanation:

  • StreamWriter("potato_recipes.txt", true) – Opens the file in append mode.
  • true ensures new data is added at the end.

🎁 Output:

More recipes have been added! 🍲

The file now contains:

πŸ₯” Potato Fries
πŸ₯” Mashed Potatoes
πŸ₯” Potato Salad
πŸ₯” Baked Potatoes
πŸ₯” Potato Soup

πŸ“‚ Working with File Class for Simpler Operations

The File class in System.IO provides easier ways to perform file operations like reading and writing.

πŸ“„ Writing with File.WriteAllText()

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string content = "πŸ₯” Potato Fries\nπŸ₯” Mashed Potatoes\nπŸ₯” Potato Salad";
        
        // Write to the file
        File.WriteAllText("potato_recipes.txt", content);
        Console.WriteLine("Recipes written using File.WriteAllText()!");
    }
}

πŸ“„ Reading with File.ReadAllText()

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Read all content from the file
        string content = File.ReadAllText("potato_recipes.txt");
        Console.WriteLine("Here are the recipes:\n" + content);
    }
}

πŸ“„ Appending with File.AppendAllText()

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string moreContent = "\nπŸ₯” Baked Potatoes\nπŸ₯” Potato Soup";
        
        // Append data
        File.AppendAllText("potato_recipes.txt", moreContent);
        Console.WriteLine("More recipes added using File.AppendAllText()!");
    }
}

⚑ Reading and Writing with FileStream

For advanced file operations, use FileStream to read and write binary data.

πŸ“„ Example of Writing Binary Data:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string data = "PotatoScript loves coding! πŸ₯”πŸ’»";
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);

        using (FileStream fs = new FileStream("potato_data.bin", FileMode.Create))
        {
            fs.Write(bytes, 0, bytes.Length);
            Console.WriteLine("Binary data written to file!");
        }
    }
}

πŸ“„ Example of Reading Binary Data:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (FileStream fs = new FileStream("potato_data.bin", FileMode.Open))
        {
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            string data = System.Text.Encoding.UTF8.GetString(bytes);
            Console.WriteLine("Data read from file: " + data);
        }
    }
}