Bird
0
0

You want to create a backup of a file only if it exists, without overwriting an existing backup. Which code snippet correctly uses File class static methods to do this?

hard🚀 Application Q15 of 15
C Sharp (C#) - File IO
You want to create a backup of a file only if it exists, without overwriting an existing backup. Which code snippet correctly uses File class static methods to do this?
Aif (File.Exists("file.txt")) File.Copy("file.txt", "backup.txt", true);
BFile.Copy("file.txt", "backup.txt");
Cif (File.Exists("file.txt") && !File.Exists("backup.txt")) File.Copy("file.txt", "backup.txt");
DFile.Copy("file.txt", "backup.txt", false);
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirements

    Backup only if original file exists and do not overwrite existing backup file.
  2. Step 2: Analyze each option

    if (File.Exists("file.txt")) File.Copy("file.txt", "backup.txt", true); overwrites backup.txt because of 'true' overwrite flag. if (File.Exists("file.txt") && !File.Exists("backup.txt")) File.Copy("file.txt", "backup.txt"); checks existence of both files and copies only if backup.txt does not exist. File.Copy("file.txt", "backup.txt"); copies without checks, risking errors or overwrites. File.Copy("file.txt", "backup.txt", false); copies without overwrite but does not check if original file exists.
  3. Final Answer:

    if (File.Exists("file.txt") && !File.Exists("backup.txt")) File.Copy("file.txt", "backup.txt"); -> Option C
  4. Quick Check:

    Check both files before copy to avoid overwrite [OK]
Quick Trick: Check both files exist before copying without overwrite [OK]
Common Mistakes:
MISTAKES
  • Not checking if backup file exists
  • Using overwrite flag incorrectly
  • Copying without checking original file existence

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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