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?
- Save Information Permanently β Unlike variables that are lost when the program ends, data stored in files stays there.
- Load and Process Large Data β Read large amounts of information from a file and process it.
- Store User Preferences β Save user settings that can be reloaded the next time the app runs.
- 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:
- File β Provides methods to perform file operations.
- StreamReader β Reads data from a file.
- 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 filepotato_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 filepotato_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);
}
}
}