C# File Replace() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
System.IO

Definition

In C#, File.Replace() puts the content of a source file into a destination file that already exists. The old destination content can be saved as a backup file.

It is built for safe saving: write the new version to a temporary file first, then replace the real file in one step. After the call, the source path no longer exists, because its file now lives at the destination path.

This is a static method of System.IO.File. Call it as File.Replace(...); there is no new File(). For an object that remembers one file, see FileInfo.

Syntax

Pass the new file, the file to replace, and a backup path. Use null for the backup when you do not want one.

C#
string folder = Path.GetTempPath();
string source = Path.Combine(folder, "codetofun-new.tmp");
string target = Path.Combine(folder, "codetofun-live.txt");
string backup = Path.Combine(folder, "codetofun-live.bak");

File.Replace(source, target, backup);
CallWhat it does
File.Replace(source, dest, backup)Replaces dest with source and saves the old dest as backup.
File.Replace(source, dest, null)Replaces dest and keeps no backup.
File.Replace(source, dest, backup, true)Same, but ignores errors while copying metadata such as attributes (the last argument is ignoreMetadataErrors).

File.Replace does in one call what you would do with Copy, Move, and Delete by hand, so a crash cannot leave a half-written file. FileInfo.Replace is the object version.

Library declarations
C#
public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName);
public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName, bool ignoreMetadataErrors);

Parameters

ParameterDescription
sourceFileNameThe file with the new content. It is moved to the destination path, so it disappears from its old path.
destinationFileNameThe file to replace. It should already exist.
destinationBackupFileNameWhere to keep the old destination content. Pass null for no backup. An old backup file is overwritten.
ignoreMetadataErrorsOptional. true ignores errors while copying attributes and timestamps to the new file.

Return Value

Return ValueDescription
voidNothing is returned. On success the destination holds the source content.

C# Examples

Example 1 — Replace a File and Keep the Old Version

Swap in new content and read the live file, the backup, and the old source path.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-replace");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string live = Path.Combine(root, "settings.txt");
        string draft = Path.Combine(root, "settings.tmp");
        string backup = Path.Combine(root, "settings.bak");

        File.WriteAllText(live, "old");
        File.WriteAllText(draft, "new");

        File.Replace(draft, live, backup);

        Console.WriteLine(File.ReadAllText(live));
        Console.WriteLine(File.ReadAllText(backup));
        Console.WriteLine(File.Exists(draft));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Two versions on disk. settings.txt is the live file with old, and settings.tmp is the draft with new.
  2. One call does the swap. Replace saves the old live content as settings.bak, then puts the draft content into settings.txt.
  3. Read the results. The live file now reads new and the backup reads old.
  4. The draft is used up. Its file became the live file, so Exists(draft) prints False.

Example 2 — Replace Without a Backup

Pass null for the backup path when the old content is not needed.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-replace-null");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string target = Path.Combine(root, "config.json");
        string temp = Path.Combine(root, "config.tmp");

        File.WriteAllText(target, "{ \"v\": 1 }");
        File.WriteAllText(temp, "{ \"v\": 2 }");

        File.Replace(temp, target, null);

        Console.WriteLine(File.ReadAllText(target));
        Console.WriteLine(Directory.GetFiles(root).Length);

        Directory.Delete(root, true);
    }
}

How It Works

  1. A config file and its draft. The target holds version one and the temp file holds version two. In C# source the quotes inside the text are written as \".
  2. null means no backup. The third argument null tells Replace not to keep the old content, so no extra file is created.
  3. The new content is live. Reading config.json shows version two.
  4. Only one file is left. The temp file was consumed and no backup was made, so GetFiles(root).Length prints 1.

Example 3 — The Safe-Save Pattern in a Loop

Save three versions the safe way: write a temp file, then replace the real file each time.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-replace-loop");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string target = Path.Combine(root, "data.txt");
        string temp = Path.Combine(root, "data.tmp");
        string backup = Path.Combine(root, "data.bak");

        File.WriteAllText(target, "v0");

        for (int i = 1; i <= 3; i++) {
            File.WriteAllText(temp, "v" + i);
            File.Replace(temp, target, backup);
        }

        Console.WriteLine(File.ReadAllText(target));
        Console.WriteLine(File.ReadAllText(backup));
        Console.WriteLine(Directory.GetFiles(root).Length);

        Directory.Delete(root, true);
    }
}

How It Works

  1. Start with a real file. data.txt holds v0, so the destination exists before the first Replace.
  2. Write the temp file, then swap. Each loop turn writes the new version to data.tmp and calls Replace. A crash while writing hurts only the temp file, never the live one.
  3. The backup moves along. Every swap overwrites the old backup with the version that was live a moment ago, so after three rounds the backup holds v2.
  4. Two files remain. The temp file is used up each time, so only data.txt and data.bak are left.

Frequently Asked Questions

It replaces the destination file with the source file. The source path disappears, and the old destination content can be saved to a backup file.
No. Pass null as destinationBackupFileName to skip it. If a backup path is given and a file is already there, that old backup is overwritten.
Replace does the swap in one step, so a crash cannot leave you with no file at all. With Delete followed by Move, there is a short moment when neither version exists at the real path.
It should. Replace is meant for swapping an existing file. If the real file may be missing, check with File.Exists and use File.Move for the first save.
Keep the source, destination, and backup on the same drive. The call is designed for same-volume swaps, and across drives it may fail.

Next: SetAttributes()

Change the FileAttributes flags of a file, such as turning ReadOnly on or off.

SetAttributes() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful