Bird
Raised Fist0

What is wrong with this code?

medium📝 Debug Q7 of Q15
C Sharp (C#) - File IO
What is wrong with this code?
string filePath = "C:\\Docs\\file.txt";
string dir = Path.GetDirectoryName(filePath);
Directory.CreateDirectory(dir);
ANo error; code creates directory from file path
BGetDirectoryName returns null if path is invalid
CCreateDirectory throws if directory exists
DfilePath string uses wrong slashes
Step-by-Step Solution
Solution:
  1. Step 1: Understand Path.GetDirectoryName usage

    GetDirectoryName extracts directory part from file path correctly.
  2. Step 2: Check Directory.CreateDirectory behavior

    CreateDirectory creates directory if missing, or does nothing if it exists, no error thrown.
  3. Final Answer:

    No error; code creates directory from file path -> Option A
  4. Quick Check:

    GetDirectoryName + CreateDirectory works safely [OK]
Quick Trick: CreateDirectory is safe even if directory exists [OK]
Common Mistakes:
MISTAKES
  • Thinking CreateDirectory throws if exists
  • Assuming GetDirectoryName returns null incorrectly
  • Confusing slash directions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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