Streams and File I/O: Advanced

More control over file reading and writing

Posted by Rodrigo Castro on December 9, 2024

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!