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.
Using statement with file streams in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
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); }
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); } } }
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.
Practice
1. What is the main purpose of using the
using statement with file streams in C#?easy
Solution
Step 1: Understand the role of
Theusingwith resourcesusingstatement ensures that the resource it wraps, like a file stream, is properly closed and disposed after the block finishes.Step 2: Apply this to file streams
File streams hold system resources that must be released to avoid file locks or memory leaks.usinghandles this automatically.Final Answer:
To automatically close and dispose the file stream after use -> Option AQuick Check:
Using = automatic resource cleanup [OK]
Hint: Using auto-closes files to avoid manual cleanup [OK]
Common Mistakes:
- Thinking using speeds up file reading
- Believing using prevents file editing
- Assuming using opens multiple files simultaneously
2. Which of the following is the correct syntax to open a file for reading using a
using statement in C#?easy
Solution
Step 1: Recognize correct
Theusingblock syntaxusingstatement requires parentheses around the resource declaration and a block of code inside braces.Step 2: Check each option
using (var fs = new FileStream("file.txt", FileMode.Open)) { } usesusing (var fs = new FileStream(...)) { }which is correct. using var fs = FileStream("file.txt", FileMode.Open); misses parentheses. using FileStream fs = new FileStream("file.txt", FileMode.Open); misses braces. using (FileStream fs = FileStream.Open("file.txt")) { } uses a non-existent methodFileStream.Open.Final Answer:
using (var fs = new FileStream("file.txt", FileMode.Open)) { } -> Option CQuick Check:
Using needs parentheses and braces [OK]
Hint: Using needs parentheses and braces for resource block [OK]
Common Mistakes:
- Omitting parentheses around resource declaration
- Forgetting braces after using statement
- Calling non-existent FileStream methods
3. What will be the output of the following C# code?
using System;
using System.IO;
class Program {
static void Main() {
using (var fs = new FileStream("test.txt", FileMode.Create)) {
byte[] data = {72, 105};
fs.Write(data, 0, data.Length);
}
using (var fs = new FileStream("test.txt", FileMode.Open)) {
byte[] buffer = new byte[2];
fs.Read(buffer, 0, buffer.Length);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(buffer));
}
}
}medium
Solution
Step 1: Write bytes to file
The code writes bytes 72 and 105 to "test.txt". These bytes represent ASCII characters 'H' and 'i'.Step 2: Read bytes and convert to string
The code reads the two bytes back and converts them to a string using ASCII encoding, resulting in "Hi".Final Answer:
Hi -> Option DQuick Check:
Bytes 72,105 = 'Hi' string [OK]
Hint: ASCII codes 72 and 105 spell 'Hi' [OK]
Common Mistakes:
- Expecting byte array printed instead of string
- Confusing byte values with characters
- Assuming file read fails without checking creation
4. Identify the error in the following code snippet that uses a
using statement with a file stream:using (FileStream fs = new FileStream("data.txt", FileMode.Open))
byte[] buffer = new byte[100];
fs.Read(buffer, 0, buffer.Length);
medium
Solution
Step 1: Check using statement syntax
Theusingstatement requires braces {} to define the scope of the resource usage.Step 2: Analyze the code block
Without braces, only the first line afterusingis considered inside the block. The buffer declaration and read call are outside, causing a compile error.Final Answer:
Missing braces {} after the using statement -> Option BQuick Check:
Using needs braces for multiple statements [OK]
Hint: Always use braces {} after using for multiple lines [OK]
Common Mistakes:
- Omitting braces for multiple statements
- Confusing FileMode.Open with invalid mode
- Thinking buffer size must be zero
5. You want to read all lines from a text file and count how many lines contain the word "error" using a
using statement with a StreamReader. Which code snippet correctly implements this?hard
Solution
Step 1: Understand reading lines with StreamReader
The correct way to read lines one by one is usingReadLine()inside a loop until it returns null.Step 2: Check each option's logic
int count = 0; using (var reader = new StreamReader("log.txt")) { string line; while ((line = reader.ReadLine()) != null) { if (line.Contains("error")) count++; } } Console.WriteLine(count); reads each line once and checks for "error" correctly. int count = 0; using var reader = new StreamReader("log.txt"); while (reader.ReadLine() != null) { if (reader.ReadLine().Contains("error")) count++; } Console.WriteLine(count); callsReadLine()twice per loop, skipping lines. int count = 0; using (StreamReader reader = new StreamReader("log.txt")) { foreach (var line in reader) { if (line.Contains("error")) count++; } } Console.WriteLine(count); tries to foreach over StreamReader which is invalid. int count = 0; using (var reader = new StreamReader("log.txt")) { string line = reader.ReadToEnd(); if (line.Contains("error")) count++; } Console.WriteLine(count); reads entire file as one string and counts only once.Final Answer:
Option A correctly reads lines and counts occurrences -> Option AQuick Check:
ReadLine loop + check line contains [OK]
Hint: Use while ((line = ReadLine()) != null) to read lines [OK]
Common Mistakes:
- Calling ReadLine() twice per loop skipping lines
- Trying to foreach over StreamReader directly
- Using ReadToEnd() and counting only once
