Streams give you fine control over reading and writing data, especially large files.
π€ Writing with FileStream
1
2
3
4
5
using (FileStream fs = new FileStream("data.bin", FileMode.Create))
{
byte[] info = { 1, 2, 3, 4, 5 };
fs.Write(info, 0, info.Length);
}
π₯ Reading with StreamReader
1
2
3
4
5
6
7
8
using (StreamReader reader = new StreamReader("hello.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
π Always Use βusingβ
The using
statement ensures the file is closed when done, even if an error occurs.
π‘ Try It!
Write several lines to a file, then read them back line by line:
1
2
3
4
5
6
7
File.WriteAllLines("fruits.txt", new[] { "Apple", "Banana", "Cherry" });
using (StreamReader sr = new StreamReader("fruits.txt"))
{
string? line;
while ((line = sr.ReadLine()) != null)
Console.WriteLine(line);
}
Next: Working with directories!