Bird
Raised Fist0

What will happen if the following C# code tries to read a non-existent file?

medium📝 Predict Output Q5 of Q15
C Sharp (C#) - File IO
What will happen if the following C# code tries to read a non-existent file?
using System;
using System.IO;
class Program {
static void Main() {
string data = File.ReadAllText("nonexistent.txt");
Console.WriteLine(data);
}
}
AThrows a System.IO.FileNotFoundException
BReturns an empty string
CCreates the file and returns null
DOutputs "File not found" to the console
Step-by-Step Solution
Solution:
  1. Step 1: Understand File.ReadAllText behavior

    This method attempts to read the entire content of the specified file.
  2. Step 2: Check file existence

    If the file does not exist, File.ReadAllText throws a FileNotFoundException.
  3. Step 3: Result of the code

    The program will throw an exception and terminate unless handled.
  4. Final Answer:

    Throws a System.IO.FileNotFoundException -> Option A
  5. Quick Check:

    File.ReadAllText throws if file missing [OK]
Quick Trick: File.ReadAllText throws if file missing [OK]
Common Mistakes:
MISTAKES
  • Assuming it returns empty string
  • Thinking it creates the file automatically
  • Expecting a console message instead of exception

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes