0
0
C Sharp (C#)programming~5 mins

Using statement with file streams in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The using statement helps you open a file safely and makes sure it closes automatically when done. This stops problems like files staying open and causing errors.

When you want to read text from a file and then close it right after.
When you need to write data to a file and ensure the file is properly closed.
When working with files in a way that requires automatic cleanup to avoid resource leaks.
When you want to avoid forgetting to close a file after using it.
Syntax
C Sharp (C#)
using (var stream = new FileStream("filename.txt", FileMode.Open))
{
    // work with the stream here
}

The using statement creates a block where the file stream is open.

When the block ends, the file stream is closed automatically, even if an error happens.

Examples
This example reads all text from file.txt and prints it. The file closes automatically after reading.
C Sharp (C#)
using (var reader = new StreamReader("file.txt"))
{
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}
This example writes a line to output.txt and closes the file automatically.
C Sharp (C#)
using (var writer = new StreamWriter("output.txt"))
{
    writer.WriteLine("Hello, world!");
}
Sample Program

This program writes two lines to example.txt using a using block, then reads and prints the file content using another using block. Both file streams close automatically.

C Sharp (C#)
using System;
using System.IO;

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

        // Write text to the file
        using (var writer = new StreamWriter(path))
        {
            writer.WriteLine("This is a test.");
            writer.WriteLine("Using statement closes the file automatically.");
        }

        // Read and print the text from the file
        using (var reader = new StreamReader(path))
        {
            string content = reader.ReadToEnd();
            Console.WriteLine(content);
        }
    }
}
OutputSuccess
Important Notes

Always use using with file streams to avoid leaving files open.

If an error happens inside the using block, the file still closes properly.

Summary

The using statement helps manage files safely and easily.

It automatically closes the file when done, preventing common mistakes.

Use it whenever you open files to read or write.