Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q6 of Q15
C Sharp (C#) - File IO
Identify the error in this code snippet:
string path = "C:\\Data";
if (Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}
APath string is incorrectly escaped
BDirectory.Exists returns null instead of bool
CCreateDirectory should be called only if directory does not exist
DCreateDirectory cannot be called inside if block
Step-by-Step Solution
Solution:
  1. Step 1: Understand Directory.Exists and CreateDirectory logic

    CreateDirectory should be called only if directory does not exist, but here it is called if it exists.
  2. Step 2: Identify logical error

    The condition is reversed; it should be if (!Directory.Exists(path)) to create directory.
  3. Final Answer:

    CreateDirectory should be called only if directory does not exist -> Option C
  4. Quick Check:

    Call CreateDirectory only if directory missing [OK]
Quick Trick: Create directory only if it doesn't exist [OK]
Common Mistakes:
MISTAKES
  • Calling CreateDirectory when directory exists
  • Misunderstanding Directory.Exists return type
  • Incorrect string escaping

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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