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

Using statement with file streams in C Sharp (C#) - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a file stream using a using statement.

C Sharp (C#)
using (var fileStream = new FileStream("example.txt", [1]))
{
    // Read or write operations
}
Drag options to blanks, or click blank then click option'
AFileAccess.Read
BFileMode.Open
CFileShare.Read
DFileOptions.None
Attempts:
3 left
💡 Hint
Common Mistakes
Using FileAccess instead of FileMode as the second argument.
Using FileShare or FileOptions in place of FileMode.
2fill in blank
medium

Complete the code to write text to a file using a StreamWriter inside a using statement.

C Sharp (C#)
using (var writer = new StreamWriter(new FileStream("output.txt", FileMode.Create)))
{
    writer.[1]("Hello, world!");
}
Drag options to blanks, or click blank then click option'
AReadLine
BClose
CWriteLine
DFlush
Attempts:
3 left
💡 Hint
Common Mistakes
Using ReadLine which reads input instead of writing.
Calling Close explicitly inside using block (not needed).
3fill in blank
hard

Fix the error in the using statement to properly dispose the FileStream after reading.

C Sharp (C#)
FileStream fs = new FileStream("data.txt", FileMode.Open);
using ([1])
{
    // Read from fs
}
Drag options to blanks, or click blank then click option'
Afs
Bnew FileStream("data.txt", FileMode.Open)
CFileStream fs
DStreamReader fs
Attempts:
3 left
💡 Hint
Common Mistakes
Creating a new FileStream inside using instead of using the existing one.
Trying to declare the variable again inside using.
4fill in blank
hard

Fill both blanks to create a using statement that reads all text from a file.

C Sharp (C#)
using (var reader = new StreamReader(new FileStream("file.txt", [1])))
{
    string content = reader.[2]();
}
Drag options to blanks, or click blank then click option'
AFileMode.Open
BReadToEnd
CReadLine
DFileMode.Create
Attempts:
3 left
💡 Hint
Common Mistakes
Using FileMode.Create which overwrites the file.
Using ReadLine which reads only one line.
5fill in blank
hard

Fill all three blanks to write multiple lines to a file using a using statement and a loop.

C Sharp (C#)
using (var writer = new StreamWriter(new FileStream("log.txt", [1])))
{
    foreach (var line in lines)
    {
        writer.[2](line);
    }
    writer.[3]();
}
Drag options to blanks, or click blank then click option'
AFileMode.Create
BWriteLine
CFlush
DFileMode.Append
Attempts:
3 left
💡 Hint
Common Mistakes
Using FileMode.Create which erases existing content.
Not calling Flush, causing data not to be saved immediately.

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