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

Reading text files 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 Reading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of reading a text file line by line
What will be the output of this C# code snippet that reads a text file line by line and prints each line?
C Sharp (C#)
using System;
using System.IO;

class Program {
    static void Main() {
        string path = "test.txt";
        File.WriteAllText(path, "Hello\nWorld\nCSharp");
        using StreamReader reader = new StreamReader(path);
        string? line;
        while ((line = reader.ReadLine()) != null) {
            Console.WriteLine(line);
        }
    }
}
A
Hello
World
CSharp
BHello World CSharp
CHelloWorldCSharp
DThrows an exception
Attempts:
2 left
💡 Hint
Remember that ReadLine reads one line at a time and Console.WriteLine prints each line on a new line.
Predict Output
intermediate
2:00remaining
Reading entire file content at once
What will this C# code print when reading the entire content of a text file at once?
C Sharp (C#)
using System;
using System.IO;

class Program {
    static void Main() {
        string path = "data.txt";
        File.WriteAllText(path, "Line1\nLine2\nLine3");
        string content = File.ReadAllText(path);
        Console.WriteLine(content);
    }
}
ALine1 Line2 Line3
B
Line1
Line2
Line3
CLine1Line2Line3
DThrows an exception
Attempts:
2 left
💡 Hint
ReadAllText reads the whole file as one string including newlines.
Predict Output
advanced
2:00remaining
Reading file with incorrect path
What happens when this C# code tries to read a file that does not exist?
C Sharp (C#)
using System;
using System.IO;

class Program {
    static void Main() {
        string path = "nofile.txt";
        string content = File.ReadAllText(path);
        Console.WriteLine(content);
    }
}
AThrows NullReferenceException
BPrints null
CPrints empty string
DThrows FileNotFoundException
Attempts:
2 left
💡 Hint
What happens if you try to read a file that does not exist?
Predict Output
advanced
2:00remaining
Reading file lines with LINQ
What is the output of this C# code that reads all lines from a file and filters lines containing 'a'?
C Sharp (C#)
using System;
using System.IO;
using System.Linq;

class Program {
    static void Main() {
        string path = "words.txt";
        File.WriteAllLines(path, new[] {"apple", "banana", "cherry", "date"});
        var lines = File.ReadLines(path).Where(line => line.Contains('a'));
        foreach (var line in lines) {
            Console.WriteLine(line);
        }
    }
}
A
apple
banana
date
B
banana
date
Ccherry
D
apple
banana
cherry
date
Attempts:
2 left
💡 Hint
Check which words contain the letter 'a'.
Predict Output
expert
2:00remaining
Reading file asynchronously
What will this C# async code print when reading a file asynchronously?
C Sharp (C#)
using System;
using System.IO;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        string path = "async.txt";
        await File.WriteAllTextAsync(path, "Async\nRead\nTest");
        string content = await File.ReadAllTextAsync(path);
        Console.WriteLine(content);
    }
}
ACompilation error
BAsync Read Test
C
Async
Read
Test
DAsyncReadTest
Attempts:
2 left
💡 Hint
Async file methods read and write the full content including newlines.

Practice

(1/5)
1. What does the File.ReadAllLines method do in C#?
easy
A. Reads the entire file content as a single string.
B. Reads all lines from a text file and returns them as a string array.
C. Writes lines to a text file.
D. Deletes the specified text file.

Solution

  1. Step 1: Understand the method purpose

    File.ReadAllLines reads a text file and returns each line as an element in a string array.
  2. Step 2: Compare with other methods

    File.ReadAllText returns the whole file as one string, not an array of lines.
  3. Final Answer:

    Reads all lines from a text file and returns them as a string array. -> Option B
  4. Quick Check:

    ReadAllLines = string array [OK]
Hint: ReadAllLines returns array of lines, not one big string [OK]
Common Mistakes:
  • Confusing ReadAllLines with ReadAllText
  • Thinking it writes to a file
  • Assuming it deletes files
2. Which of the following is the correct syntax to read all text from a file named "data.txt" using File.ReadAllText?
easy
A. string content = File.ReadAllText("data.txt");
B. string content = File.ReadAllLines("data.txt");
C. string[] content = File.ReadAllText("data.txt");
D. string[] content = File.ReadAllLines("data.txt");

Solution

  1. Step 1: Identify method return types

    File.ReadAllText returns a single string, so the variable must be string.
  2. Step 2: Match syntax with variable type

    string content = File.ReadAllText("data.txt"); uses string variable with ReadAllText correctly. Options B and D mismatch method and variable types. string[] content = File.ReadAllText("data.txt"); tries to assign string to string array.
  3. Final Answer:

    string content = File.ReadAllText("data.txt"); -> Option A
  4. Quick Check:

    ReadAllText returns string, so variable is string [OK]
Hint: Match method return type with variable type [OK]
Common Mistakes:
  • Assigning ReadAllText to string array
  • Using ReadAllLines but expecting string
  • Wrong variable type for method
3. What will be the output of this C# code if the file "example.txt" contains three lines: "Hello", "World", "!"?
string[] lines = File.ReadAllLines("example.txt");
Console.WriteLine(lines.Length);
medium
A. 3
B. Hello World !
C. 1
D. Error at runtime

Solution

  1. Step 1: Understand ReadAllLines output

    The method returns an array with one element per line in the file. Here, 3 lines means array length is 3.
  2. Step 2: Analyze Console.WriteLine output

    Printing lines.Length outputs the number of lines, which is 3.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Array length = number of lines = 3 [OK]
Hint: ReadAllLines length equals number of lines in file [OK]
Common Mistakes:
  • Expecting content printed instead of length
  • Confusing ReadAllText with ReadAllLines
  • Assuming runtime error without cause
4. Identify the error in this code snippet that reads all lines from "notes.txt":
string[] lines = File.ReadAllLines(notes.txt);
foreach (string line in lines)
{
    Console.WriteLine(line);
}
medium
A. Console.WriteLine cannot print strings.
B. File.ReadAllLines returns a string, not string array.
C. foreach loop syntax is incorrect.
D. Missing quotes around the file name in ReadAllLines.

Solution

  1. Step 1: Check file path syntax

    The file name must be a string literal, so it needs quotes: "notes.txt".
  2. Step 2: Verify other code parts

    File.ReadAllLines returns string array, foreach syntax is correct, and Console.WriteLine can print strings.
  3. Final Answer:

    Missing quotes around the file name in ReadAllLines. -> Option D
  4. Quick Check:

    File path must be in quotes [OK]
Hint: File names must be in quotes in method calls [OK]
Common Mistakes:
  • Forgetting quotes around file path
  • Thinking ReadAllLines returns string
  • Misunderstanding foreach syntax
5. You want to read a text file and count how many lines contain the word "error" (case insensitive). Which code snippet correctly does this?
hard
A. var lines = File.ReadAllLines("log.txt"); int count = 0; foreach(var line in lines) { if(line.Contains("error")) count++; }
B. string content = File.ReadAllText("log.txt"); int count = content.Split('\n').Count(line => line.Contains("error"));
C. var lines = File.ReadAllLines("log.txt"); int count = lines.Count(line => line.ToLower().Contains("error"));
D. string[] lines = File.ReadAllText("log.txt").Split('\n'); int count = lines.Count(line => line.Contains("error"));

Solution

  1. Step 1: Choose method to read lines

    File.ReadAllLines returns an array of lines, perfect for line-by-line processing.
  2. Step 2: Count lines with "error" case-insensitive

    var lines = File.ReadAllLines("log.txt"); int count = lines.Count(line => line.ToLower().Contains("error")); converts each line to lowercase and checks if it contains "error", then counts matches using LINQ.
  3. Step 3: Check other options

    string content = File.ReadAllText("log.txt"); int count = content.Split('\n').Count(line => line.Contains("error")); uses ReadAllText but misses case-insensitive check. var lines = File.ReadAllLines("log.txt"); int count = 0; foreach(var line in lines) { if(line.Contains("error")) count++; } misses case-insensitive check. string[] lines = File.ReadAllText("log.txt").Split('\n'); int count = lines.Count(line => line.Contains("error")); incorrectly assigns ReadAllText to string array without ToLower.
  4. Final Answer:

    var lines = File.ReadAllLines("log.txt"); int count = lines.Count(line => line.ToLower().Contains("error")); -> Option C
  5. Quick Check:

    Use ReadAllLines + ToLower + Count for case-insensitive search [OK]
Hint: Use ReadAllLines and ToLower for case-insensitive line checks [OK]
Common Mistakes:
  • Ignoring case sensitivity
  • Using ReadAllText but treating as array
  • Not converting lines to lowercase