File I/O & disposable streams

🔷 C# Programming Lesson 15 Advanced

C# interacts with storage drives using file streams. C# provides the using keyword to automatically dispose of and close stream resources after execution.

1 Auto-Disposing Resources via using Declarations

Failing to close file streams causes memory leaks and file lock issues. C# implements the **`using` declaration** (objects that implement the `IDisposable` interface). When execution leaves the scope of the using block, the compiler automatically calls `Dispose()` to close and release the resource, ensuring memory safety even if exceptions occur.

2 File Operations Code

Let's run a program writing text to a file and reading it back using `StreamWriter` and `StreamReader`:

C# — File Operations ▶ Run Code
using System;
using System.IO; // Required for file operations

class Program {
    static void Main() {
        string path = "demo.txt";

        // Auto-disposing StreamWriter
        using (StreamWriter writer = new StreamWriter(path)) {
            writer.WriteLine("C# File Operations are safe and clean!");
        } // 'writer' is automatically closed and disposed of here

        // Auto-disposing StreamReader
        using (StreamReader reader = new StreamReader(path)) {
            string content = reader.ReadToEnd();
            Console.WriteLine("File Content: " + content);
        }
    }
}
3 Code Challenge
Challenge: Write a program that writes three numbers to a file named `numbers.txt`. Open the file, read the numbers line-by-line, parse them as integers, and print their computed sum. Ensure you use `using` declarations.