Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Using statement with file streams in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
File Stream Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of reading file lines with using statement
What is the output of this C# code snippet when the file test.txt contains three lines:
Line1
Line2
Line3?
C Sharp (C#)
using System;
using System.IO;

class Program {
    static void Main() {
        using (var reader = new StreamReader("test.txt")) {
            string line;
            while ((line = reader.ReadLine()) != null) {
                Console.WriteLine(line);
            }
        }
    }
}
ANo output, throws exception
BLine1 Line2 Line3
CLine1\nLine2\nLine3
DLine3\nLine2\nLine1
Attempts:
2 left
💡 Hint
Think about how StreamReader.ReadLine() reads lines and how Console.WriteLine outputs them.
Predict Output
intermediate
2:00remaining
Output of writing to a file with using statement
What will be the content of output.txt after running this C# code?
C Sharp (C#)
using System;
using System.IO;

class Program {
    static void Main() {
        using (var writer = new StreamWriter("output.txt")) {
            writer.WriteLine("Hello");
            writer.WriteLine("World");
        }
    }
}
AHello\nWorld\n
BHello World
CHelloWorld
DFile is empty
Attempts:
2 left
💡 Hint
Remember that WriteLine adds a new line after the text.
Predict Output
advanced
2:00remaining
Behavior of nested using statements with file streams
What is the output of this C# program?
C Sharp (C#)
using System;
using System.IO;

class Program {
    static void Main() {
        using (var writer = new StreamWriter("nested.txt")) {
            writer.WriteLine("Start");
            using (var reader = new StreamReader("nested.txt")) {
                string content = reader.ReadToEnd();
                Console.WriteLine(string.IsNullOrEmpty(content) ? "Empty" : content);
            }
            writer.WriteLine("End");
        }
    }
}
AThrows IOException
BStart\nEnd\n
CStart
DEmpty
Attempts:
2 left
💡 Hint
Think about when the StreamWriter flushes data to the file and when the StreamReader reads it.
Predict Output
advanced
2:00remaining
Output of using statement with file stream and manual flush
What will this program print?
C Sharp (C#)
using System;
using System.IO;

class Program {
    static void Main() {
        using (var writer = new StreamWriter("flush.txt")) {
            writer.WriteLine("Line1");
            writer.Flush();
            using (var reader = new StreamReader("flush.txt")) {
                Console.WriteLine(reader.ReadToEnd());
            }
        }
    }
}
AEmpty
BLine1\n
CThrows IOException
DLine1
Attempts:
2 left
💡 Hint
Consider what Flush() does to the StreamWriter buffer.
🧠 Conceptual
expert
2:00remaining
Why is using statement important with file streams?
Which of the following best explains why the using statement is important when working with file streams in C#?
AIt automatically closes and disposes the file stream to free resources and avoid file locks.
BIt improves the speed of file reading and writing by caching data.
CIt allows multiple threads to access the file stream simultaneously without errors.
DIt encrypts the file content automatically for security.
Attempts:
2 left
💡 Hint
Think about resource management and what happens if files are not closed properly.

Practice

(1/5)
1. What is the main purpose of using the using statement with file streams in C#?
easy
A. To automatically close and dispose the file stream after use
B. To open multiple files at the same time
C. To read the file contents faster
D. To prevent the file from being edited

Solution

  1. Step 1: Understand the role of using with resources

    The using statement ensures that the resource it wraps, like a file stream, is properly closed and disposed after the block finishes.
  2. Step 2: Apply this to file streams

    File streams hold system resources that must be released to avoid file locks or memory leaks. using handles this automatically.
  3. Final Answer:

    To automatically close and dispose the file stream after use -> Option A
  4. Quick 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
A. using FileStream fs = new FileStream("file.txt", FileMode.Open);
B. using var fs = FileStream("file.txt", FileMode.Open);
C. using (var fs = new FileStream("file.txt", FileMode.Open)) { }
D. using (FileStream fs = FileStream.Open("file.txt")) { }

Solution

  1. Step 1: Recognize correct using block syntax

    The using statement requires parentheses around the resource declaration and a block of code inside braces.
  2. Step 2: Check each option

    using (var fs = new FileStream("file.txt", FileMode.Open)) { } uses using (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 method FileStream.Open.
  3. Final Answer:

    using (var fs = new FileStream("file.txt", FileMode.Open)) { } -> Option C
  4. Quick 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
A. Error: File not found
B. 72,105
C. System.Byte[]
D. Hi

Solution

  1. Step 1: Write bytes to file

    The code writes bytes 72 and 105 to "test.txt". These bytes represent ASCII characters 'H' and 'i'.
  2. 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".
  3. Final Answer:

    Hi -> Option D
  4. Quick 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
A. FileMode.Open is invalid for reading
B. Missing braces {} after the using statement
C. Buffer size should be 0
D. FileStream cannot be used with using

Solution

  1. Step 1: Check using statement syntax

    The using statement requires braces {} to define the scope of the resource usage.
  2. Step 2: Analyze the code block

    Without braces, only the first line after using is considered inside the block. The buffer declaration and read call are outside, causing a compile error.
  3. Final Answer:

    Missing braces {} after the using statement -> Option B
  4. Quick 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
A. 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);
B. int count = 0; using var reader = new StreamReader("log.txt"); while (reader.ReadLine() != null) { if (reader.ReadLine().Contains("error")) count++; } Console.WriteLine(count);
C. int count = 0; using (StreamReader reader = new StreamReader("log.txt")) { foreach (var line in reader) { if (line.Contains("error")) count++; } } Console.WriteLine(count);
D. int count = 0; using (var reader = new StreamReader("log.txt")) { string line = reader.ReadToEnd(); if (line.Contains("error")) count++; } Console.WriteLine(count);

Solution

  1. Step 1: Understand reading lines with StreamReader

    The correct way to read lines one by one is using ReadLine() inside a loop until it returns null.
  2. 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); calls ReadLine() 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.
  3. Final Answer:

    Option A correctly reads lines and counts occurrences -> Option A
  4. Quick 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