File.Exists() / File.Delete() / File.Copy()
| Since: | C# 1.0(2002) |
|---|
How to use File.Exists() to check if a file exists, File.Delete() to delete a file, File.Copy() to copy a file, and File.Move() to move a file.
Syntax
using System.IO; // Checks whether a file exists (returns true or false). bool exists = File.Exists(string path); // Deletes a file. Does nothing if the file does not exist. File.Delete(string path); // Copies a file. File.Copy(string sourceFileName, string destFileName); // Copies a file (overwrite allowed when true). File.Copy(string sourceFileName, string destFileName, bool overwrite); // Moves a file (also used for renaming). File.Move(string sourceFileName, string destFileName); // Moves a file (overwrite allowed when true, .NET 5 and later). File.Move(string sourceFileName, string destFileName, bool overwrite);
Method List
| Method | Description |
|---|---|
| File.Exists(path) | Returns true if a file exists at the specified path, false otherwise. |
| File.Delete(path) | Deletes the specified file. Does not throw an exception if the file does not exist. |
| File.Copy(src, dest) | Copies src to dest. Throws IOException if dest already exists. |
| File.Copy(src, dest, overwrite) | Setting overwrite to true allows overwriting an existing file. |
| File.Move(src, dest) | Moves a file to a new location. Changing the file name acts as a rename. |
| File.GetLastWriteTime(path) | Returns the last write time of the file as a DateTime. |
Sample Code
Program.cs
using System;
using System.IO;
string source = "original.txt";
string copyDest = "copy.txt";
string moveDest = "moved.txt";
File.WriteAllText(source, "This is a test file.");
Console.WriteLine(File.Exists(source)); // True
Console.WriteLine(File.Exists("none.txt")); // False
// Copies a file.
File.Copy(source, copyDest);
Console.WriteLine($"Copy done: {File.Exists(copyDest)}"); // True
// Overwrite requires overwrite: true.
File.Copy(source, copyDest, overwrite: true);
Console.WriteLine("Overwrite copy done.");
// Moves (or renames) a file.
File.Move(copyDest, moveDest);
Console.WriteLine($"Copy dest after move: {File.Exists(copyDest)}"); // False
Console.WriteLine($"Move dest after move: {File.Exists(moveDest)}"); // True
DateTime lastWrite = File.GetLastWriteTime(source);
Console.WriteLine($"Last write: {lastWrite:yyyy/MM/dd HH:mm:ss}");
// Deletes files.
File.Delete(source);
File.Delete(moveDest);
Console.WriteLine($"After delete: {File.Exists(source)}"); // False
Run the following command:
dotnet script file_exists_delete_copy.csx True False Copy done: True Overwrite copy done. Copy dest after move: False Move dest after move: True Last write: 2024/01/15 14:30:00 After delete: False
Practical Pattern: File Backup and Cleanup
A pattern for creating a timestamped backup before updating a configuration file, then cleaning up old backups.
FileBackup.cs
using System;
using System.IO;
string configFile = "config.json";
string backupFile = $"config_{DateTime.Now:yyyyMMdd_HHmmss}.bak";
File.WriteAllText(configFile, "{\"theme\": \"dark\"}");
Console.WriteLine("Config file created.");
if (File.Exists(configFile))
{
File.Copy(configFile, backupFile);
Console.WriteLine($"Backup created: {backupFile}");
}
// Updates the configuration file.
File.WriteAllText(configFile, "{\"theme\": \"light\", \"fontSize\": 14}");
Console.WriteLine("Config file updated.");
// Verifies the backup exists.
Console.WriteLine($"Backup exists: {File.Exists(backupFile)}");
Console.WriteLine($"Backup write time: {File.GetLastWriteTime(backupFile):yyyy/MM/dd HH:mm:ss}");
// Cleanup.
File.Delete(configFile);
File.Delete(backupFile);
Run the following command:
dotnet script file_backup.csx Config file created. Backup created: config_20240115_143045.bak Config file updated. Backup exists: True Backup write time: 2024/01/15 14:30:45
Practical Pattern: Safe File Operations with Exception Handling
A pattern that combines File.Exists() with exception handling to safely handle TOCTOU (time-of-check to time-of-use) race conditions.
SafeFileOps.cs
using System;
using System.IO;
// Safe file delete: existence check + exception handling
static bool TryDeleteFile(string path)
{
try
{
File.Delete(path);
return true;
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine($"Access denied: {ex.Message}");
return false;
}
catch (IOException ex)
{
Console.WriteLine($"IO error: {ex.Message}");
return false;
}
}
// Safe file copy: checks source before overwriting
static bool TryCopyFile(string src, string dest, bool overwrite = false)
{
if (!File.Exists(src))
{
Console.WriteLine($"Source not found: {src}");
return false;
}
try
{
File.Copy(src, dest, overwrite);
return true;
}
catch (IOException ex)
{
Console.WriteLine($"Copy error: {ex.Message}");
return false;
}
}
// Test
File.WriteAllText("source.txt", "data");
bool ok1 = TryCopyFile("source.txt", "dest.txt");
bool ok2 = TryCopyFile("none.txt", "dest.txt"); // fails
bool ok3 = TryDeleteFile("source.txt");
bool ok4 = TryDeleteFile("dest.txt");
Console.WriteLine($"Copy1: {ok1}, Copy2: {ok2}, Delete1: {ok3}, Delete2: {ok4}");
Run the following command:
dotnet script safe_file_ops.csx Source not found: none.txt Copy1: True, Copy2: False, Delete1: True, Delete2: True
Common Mistakes
Common Mistake 1: IOException When Overwriting Without overwrite Flag
If the destination file already exists, File.Copy() throws an IOException unless overwrite is specified.
using System;
using System.IO;
File.WriteAllText("a.txt", "data1");
File.WriteAllText("b.txt", "data2"); // Destination file already exists.
// NG: Throws IOException because the destination exists.
File.Copy("a.txt", "b.txt");
Run the following command:
dotnet run Unhandled exception. System.IO.IOException: The file 'b.txt' already exists.
The following example demonstrates this:
using System;
using System.IO;
File.WriteAllText("a.txt", "data1");
File.WriteAllText("b.txt", "data2");
// OK: Pass overwrite: true to allow overwriting.
File.Copy("a.txt", "b.txt", overwrite: true);
Console.WriteLine("Overwrite copy done.");
// Cleanup.
File.Delete("a.txt");
File.Delete("b.txt");
Run the following command:
dotnet run Overwrite copy done.
Common Mistake 2: Deleting a Read-Only File
Trying to delete a read-only file with File.Delete() throws an UnauthorizedAccessException.
using System;
using System.IO;
File.WriteAllText("readonly.txt", "data");
File.SetAttributes("readonly.txt", FileAttributes.ReadOnly);
// NG: Cannot delete a read-only file.
File.Delete("readonly.txt"); // UnauthorizedAccessException is thrown.
Run the following command:
dotnet run Unhandled exception. System.UnauthorizedAccessException: Access to the path 'readonly.txt' is denied.
The following example demonstrates this:
using System;
using System.IO;
File.WriteAllText("readonly.txt", "data");
File.SetAttributes("readonly.txt", FileAttributes.ReadOnly);
// OK: Remove the read-only attribute before deleting.
File.SetAttributes("readonly.txt", FileAttributes.Normal);
File.Delete("readonly.txt");
Console.WriteLine("Deleted.");
Run the following command:
dotnet run Deleted.
Overview
File.Exists() has a TOCTOU (time-of-check to time-of-use) race condition issue. Another process may delete the file between the existence check and the actual operation, so always combine existence checks with exception handling.
File.Delete() does nothing when the file does not exist, but throws an UnauthorizedAccessException for read-only files. For reading and writing file contents, see File.ReadAllText() / WriteAllText(). For line-by-line stream processing, see StreamReader / StreamWriter.
If you find any errors or copyright issues, please contact us.