Question

Rename a File in C#: File.Move and Safe Rename Patterns

csharpfilerename

Question

How can I rename a file in C#? Show the recommended approach, including how to specify the original and new file paths safely.

Short Answer

By the end of this page, you will know how to rename a file in C# using System.IO.File.Move, build correct paths, handle existing destination files, and avoid common filesystem errors.

Concept

Renaming a file means changing its path's file-name portion. In C#, the usual API is File.Move from the System.IO namespace.

File.Move(sourcePath, destinationPath);

Although its name is Move, this method also performs a rename when the source and destination are in the same directory. A file system treats a rename as moving an item from its old path to its new path.

For example, changing:

C:\Reports\draft.txt

to:

C:\Reports\final.txt

is a move within C:\Reports.

This matters because files are external resources: they can be missing, locked by another program, protected by permissions, or already present at the destination. Reliable programs validate inputs and handle these conditions rather than assuming every file operation succeeds.

Mental Model

Think of a file path as a mailing address. Renaming a file is like changing the name on a mailbox while keeping it on the same street.

  • The source path is the file's current address.
  • The destination path is its new address.
  • File.Move tells the operating system to update that address.

If another mailbox already has the destination name, the operating system needs clear instructions about whether it may replace it. If the file is currently being used by someone else, the rename may have to wait or fail.

Take Quiz

Syntax and Examples

Import the file-system namespace:

using System.IO;

The basic syntax is:

File.Move(string sourceFileName, string destFileName);

Rename a file in the same folder

using System;
using System.IO;

string folder = @"C:\Reports";
string oldPath = Path.Combine(folder, "draft.txt");
string newPath = Path.Combine(folder, "final.txt");

File.Move(oldPath, newPath);

Console.WriteLine("File renamed.");

Path.Combine creates the path using the correct directory separator for the current operating system. Avoid manually joining path pieces with "\\" or "/" when possible.

Rename and replace an existing file

On modern .NET versions, use the overload that accepts overwrite:

File.Move(oldPath, newPath, overwrite: true);

This replaces the destination file if it exists. Use this only when replacing that file is truly intended.

Change only the file name while keeping its directory

string oldPath = @"C:\Reports\draft.txt";
string directory = Path.GetDirectoryName(oldPath)!;
string newPath = Path.Combine(directory, "final.txt");

File.Move(oldPath, newPath);

The ! tells the compiler that directory is expected not to be null. For a complete program that accepts arbitrary paths, validate it before using it.

Step by Step Execution

Consider this example:

using System;
using System.IO;

string sourcePath = Path.Combine("data", "today.csv");
string destinationPath = Path.Combine("data", "processed.csv");

if (!File.Exists(sourcePath))
{
    Console.WriteLine("The source file does not exist.");
    return;
}

File.Move(sourcePath, destinationPath, overwrite: true);
Console.WriteLine("Rename complete.");

Step by step:

  1. Path.Combine("data", "today.csv") creates a path to today.csv inside the data directory.
  2. A second path is created for the new name, processed.csv.
  3. File.Exists(sourcePath) checks whether the original file exists.
  4. If it does not exist, the program prints a message and stops with return.
  5. If it exists, File.Move renames it. Because overwrite: true is supplied, an existing processed.csv is replaced.
  6. The success message is printed only after File.Move completes without an exception.

After a successful move, today.csv no longer exists at its old path; the file is now available as processed.csv.

Real World Use Cases

  • Report generation: rename report.tmp to report.csv after successfully writing the report.
  • Upload processing: rename an incoming file from invoice.pdf.uploading to invoice.pdf once validation finishes.
  • Archiving: rename files with a timestamp, such as app.log to app-2025-03-08.log.
  • Batch imports: move completed files from an incoming folder into a processed folder. This is both a move and a possible rename.
  • User-managed documents: allow a desktop application to rename a note, image, or export file selected by the user.
  • Data pipelines: give files a final name only after their contents are complete, so another process does not read a partially written file.
Take Quiz

Real Codebase Usage

Production code usually separates the requested new name from the full destination path, validates the name, and uses guard clauses before changing the file system.

using System;
using System.IO;

public static class FileRenamer
{
    public static void Rename(string sourcePath, string newFileName)
    {
        if (string.IsNullOrWhiteSpace(sourcePath))
            throw new ArgumentException("A source path is required.", nameof(sourcePath));

        if (!File.Exists(sourcePath))
            throw new FileNotFoundException("The source file was not found.", sourcePath);

        if (string.IsNullOrWhiteSpace(newFileName))
            throw new ArgumentException("A new file name is required.", nameof(newFileName));

        if (newFileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            throw new ArgumentException("The new file name contains invalid characters.", nameof(newFileName));

        string? directory = Path.GetDirectoryName(sourcePath);
        if (string.IsNullOrEmpty(directory))
            throw new ArgumentException("The source path must include a directory.", nameof(sourcePath));

        string destinationPath = Path.Combine(directory, newFileName);
        File.Move(sourcePath, destinationPath, overwrite: false);
    }
}

Common project patterns include:

  • Guard clauses: reject missing paths or invalid names early.
  • Validation: use Path.GetInvalidFileNameChars() for a file-name input.
  • Intentional overwrite policy: default to overwrite: false; only enable replacement when the business rule allows it.
  • Exception handling at the application boundary: a command-line tool, web endpoint, or UI can convert IOException and UnauthorizedAccessException into useful user messages.
  • Logging: record source and destination paths after a successful operation, while avoiding exposure of sensitive paths in public logs.

Do not use File.Exists as the only protection against errors. The file system can change after the check, so File.Move can still throw an exception. The check improves the message, while exception handling maintains correctness.

Common Mistakes

Using only a new file name as the destination

This may move the file into the application's current working directory instead of keeping it in the original folder.

// Risky: destination directory depends on the current working directory.
File.Move(@"C:\Reports\draft.txt", "final.txt");

Build the destination from the source directory instead:

string source = @"C:\Reports\draft.txt";
string destination = Path.Combine(Path.GetDirectoryName(source)!, "final.txt");
File.Move(source, destination);

Assuming an existing destination is always replaced

// May throw IOException when final.txt already exists.
File.Move(oldPath, newPath);

Use the overwrite overload when replacement is intended and supported by your target .NET version:

File.Move(oldPath, newPath, overwrite: true);

Otherwise, decide explicitly whether to stop, generate a unique name, or delete the destination first.

Concatenating paths manually

string path = folder + "\\" + fileName;

This can create duplicate or incorrect separators and is less portable. Prefer:

string path = Path.Combine(folder, fileName);

Forgetting that a file can be locked

A file opened by another application or process may not be renameable. File.Move can throw IOException. Close streams with using before trying to rename a file.

using (FileStream stream = File.OpenRead(sourcePath))
{
    // Read the file here.
}

// The stream is disposed, so it is safer to rename now.
File.Move(sourcePath, destinationPath);

Trying to rename a directory with File.Move

Use Directory.Move for folders:

Directory.Move(oldDirectoryPath, newDirectoryPath);

Treating a rename as a copy

After File.Move succeeds, the old path is gone. If you need both files, use File.Copy instead.

Comparisons

TaskRecommended APIWhat happens to the original?
Rename a file in the same folderFile.Move(oldPath, newPath)The old path is removed.
Move a file to another folderFile.Move(oldPath, newPath)The old path is removed.
Copy a fileFile.Copy(sourcePath, destinationPath)The original remains.
Delete a fileFile.Delete(path)The file is removed.
Rename or move a directoryDirectory.Move(oldPath, newPath)The old directory path is removed.

File.Move is the right choice when there should be one resulting file at the destination. File.Copy is the right choice when the original must remain available.

ApproachBest useCaution
File.Move(source, destination)Destination must not already existThrows if it exists.
File.Move(source, destination, true)Replacing destination is intentionalExisting destination data is lost.
Check File.Exists then moveBetter messages or business rulesStill handle exceptions because conditions can change.
Take Quiz

Cheat Sheet

using System.IO;

// Rename in the same folder
File.Move(oldPath, newPath);

// Rename or move and replace destination if it exists
File.Move(oldPath, newPath, overwrite: true);

// Build a destination in the same directory
string newPath = Path.Combine(
    Path.GetDirectoryName(oldPath)!,
    "new-name.txt");

// Check a source file
bool exists = File.Exists(oldPath);

// Get path parts
string? folder = Path.GetDirectoryName(oldPath);
string name = Path.GetFileName(oldPath);
string extension = Path.GetExtension(oldPath);

// Rename a directory instead
Directory.Move(oldFolder, newFolder);

Rules to remember:

  • Use File.Move for both file moves and file renames.
  • A rename is a move to a different path, usually in the same directory.
  • Use Path.Combine instead of string concatenation for paths.
  • The source must exist.
  • An existing destination causes an error unless you deliberately allow overwrite.
  • Be prepared for IOException and UnauthorizedAccessException in real applications.
  • If you need to preserve the original file, use File.Copy, not File.Move.

FAQ

How do I rename a file without moving it in C#?

Use File.Move and create the destination path in the same directory as the source file. Renaming is implemented as a move to a new path.

Does File.Move overwrite an existing file?

The two-argument overload does not overwrite an existing destination file. On supported modern .NET versions, use File.Move(source, destination, overwrite: true) when replacement is intentional.

Can I rename a file extension in C#?

Yes. Create a destination path with the new extension and call File.Move.

File.Move("report.txt", "report.csv");

Changing an extension changes only the name; it does not convert the file's content format.

Why does File.Move throw an IOException?

Typical causes include a missing source file, an existing destination file, a locked file, or another file-system conflict. Check the exception and ensure streams are closed.

How do I rename a file while keeping its folder?

Get the source directory with Path.GetDirectoryName, then use Path.Combine with the new file name.

Can I rename a folder using File.Move?

No. Use Directory.Move for directories.

Is File.Exists required before calling File.Move?

No. It can provide a clearer message, but it cannot guarantee the file will still exist when the move occurs. Handle exceptions from File.Move as well.

Does renaming a file change its contents?

No. A rename changes the file's path and name, not its bytes or format.

Take Quiz

Mini Project

Description

Build a small console utility that renames a file in place. The utility takes an existing file path and a new file name, keeps the file in its current directory, prevents accidental replacement, and reports common errors clearly.

Goal

Create a console program that safely renames an existing file to a user-provided name.

Requirements

Requirement 1

Take Quiz

Keep learning

Related questions

View more