iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🛠️

【C#】Does File.Replace Perform Atomic Updates?

に公開
2026/02/03

Let's investigate whether the file replacement of File.Replace is performed atomically.

What is atomic?

In short, it means ensuring that the file does not get corrupted even if some failure (power outage, application crash, etc.) occurs during the update. Especially if only part of the file is updated during writing, it becomes an invalid file, so this refers to the measure to prevent that.
In this article, we will call such an update that achieves the above an "atomic update".

General method of atomic update

If you write directly, it may be corrupted in case of failure, so we take the following steps:

  1. Write new content to a temporary file.
  2. Replace the original file with the temporary file.

First, when writing to the temporary file, the original file is not modified, so even if a failure occurs, the original is safe. Next, when replacing the temporary file with the original file, we use the "file replacement" API provided by the OS. This API (generally) behaves by rewriting directory entries. Since this operation is performed atomically at the OS level, even if a failure occurs, the original file will not be corrupted (even if not, it happens much faster than direct writing, so the chance of failure is low).

Atomic update in C#

Now that we understand the importance of atomic updates, the question is what is the correct way to do it in C#? Writing the above steps straightforwardly gives the following code. (Exception handling omitted)

var contents = "new content";
var original = "data.txt";
var backup = "data.txt.bak";
var temp = "data.txt.tmp";

// 1. Write new content to temporary file
File.WriteAllText(temp, contents);
// 2. Replace temporary file with original file
File.Replace(temp, original, backup);

If File.Replace behaves as expected, the above code achieves an atomic update. And that's the subject of this investigation: What does it actually do?

Tracing the behavior of File.Replace

Let's trace the dotnet code.

First, let's start with File.Replace. It is in System.IO.[1]

// System.IO.File
public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName, bool ignoreMetadataErrors)
{
    // omitted
    FileSystem.ReplaceFile(
        Path.GetFullPath(sourceFileName),
        Path.GetFullPath(destinationFileName),
        destinationBackupFileName != null ? Path.GetFullPath(destinationBackupFileName) : null,
        ignoreMetadataErrors);
}

The FileSystem.ReplaceFile called here branches between Windows and Unix.

On Windows

It is in FileSystem.Windows.cs.[2]

public static void ReplaceFile(string sourceFullPath, string destFullPath, string? destBackupFullPath, bool ignoreMetadataErrors)
{
    int flags = ignoreMetadataErrors ? Interop.Kernel32.REPLACEFILE_IGNORE_MERGE_ERRORS : 0;

    if (!Interop.Kernel32.ReplaceFile(destFullPath, sourceFullPath, destBackupFullPath, flags, IntPtr.Zero, IntPtr.Zero))
    {
        // omitted
    }
}

It calls the Windows API ReplaceFile via Interop.Kernel32.ReplaceFile.

Regarding this ReplaceFile, the official documentation does not specifically mention atomicity. However, the Transactional NTFS (TxF) page has the following description:

(English version): Many applications which deal with "document-like" data tend to load the entire document into memory, operate on it, and then write it back out to save the changes. The needed atomicity here is that the changes either are completely applied or not applied at all, as an inconsistent state would render the file corrupt. A common approach is to write the document to a new file, then replace the original file with the new one. One method to do this is with the ReplaceFile API.

(Japanese version): Many applications that handle "document-like" data tend to load the entire document into memory, operate on it, and then write it back to save changes. The required atomicity here is that changes are either completely applied or not applied at all, since an inconsistent state would corrupt the file. A common method is to write the document to a new file and then replace the original file with the new one. One way to do this is the ReplaceFile API.

From this description, it seems reasonable to interpret that the WinAPI ReplaceFile supports atomic updates.

On Unix

Let's look at FileSystem.Unix.cs.[3]

public static void ReplaceFile(string sourceFullPath, string destFullPath, string? destBackupFullPath, bool ignoreMetadataErrors /* unused */)
{
    // omitted
    if (destBackupFullPath != null)
    {
        if (Interop.Sys.Unlink(destBackupFullPath) != 0)
        {
            // error handling
        }
        LinkOrCopyFile(destFullPath, destBackupFullPath);
    }
    else
    {
        if (Interop.Sys.Stat(destFullPath, out _) != 0)
        {
            // error handling
        }
    }
    Interop.CheckIo(Interop.Sys.Rename(sourceFullPath, destFullPath));
}

private static void LinkOrCopyFile (string sourceFullPath, string destFullPath)
{
    if (Interop.Sys.Link(sourceFullPath, destFullPath) >= 0)
        return;
    Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
    if (/* omitted */)
    {
        CopyFile(sourceFullPath, destFullPath, overwrite: false);
    }
    else
    {
        // error handling
    }
}

The main flow is:

  • If a backup file is specified, delete the existing backup file.
  • Copy the original file to the backup file (if specified).
  • Replace the temporary file with the original file using rename.

This also appears to achieve atomic updates.

Let's dig deeper just to be sure. Looking at Interop.Sys.Rename, it looks like this:[4]

[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_Rename", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)]
internal static partial int Rename(string oldPath, string newPath);

Here, Libraries.SystemNative points to libSystem.Native.so.[5]

internal const string SystemNative = "libSystem.Native";

The code of this libSystem.Native.so is also of course published; it is here. Inside it, pal_io.c contains the implementation of SystemNative_Rename.[6]

int32_t SystemNative_Rename(const char* oldPath, const char* newPath)
{
    int32_t result;
    while ((result = rename(oldPath, newPath)) < 0 && errno == EINTR);
    return result;
}

It simply calls rename. rename is a POSIX standard function, and its specification is here.

(English original): This rename() function is equivalent for regular files to that defined by the ISO C standard. Its inclusion here expands that definition to include actions on directories and specifies behavior when the new parameter names a file that already exists. That specification requires that the action of the function be atomic.

(Japanese translation): This rename() function is equivalent for regular files to that defined by the ISO C standard. Its inclusion here expands that definition to include actions on directories and specifies behavior when the new parameter names a file that already exists. That specification requires that the action of the function be atomic.

Thus, atomic updates are guaranteed by the specification.

Conclusion

  • On Windows, File.Replace uses ReplaceFile; on Unix, it uses rename.
  • On Windows, it is not explicitly stated, but from the description as a replacement for TxF, atomic updates are considered supported.
  • On Unix, atomic updates are guaranteed by the POSIX standard.
  • Therefore, it is considered that C#'s File.Replace performs atomic updates.

Supplementary Note

Despite extensive searching, I could only find baseless answers on StackOverflow, and the articles that appeared were generally old, so I conducted this investigation anew.

References

脚注
  1. https://github.com/dotnet/runtime/blob/9fb66db5ab5baae0269a0e5e2a79ee0e6f6b8f81/src/libraries/System.Private.CoreLib/src/System/IO/File.cs#L1023-L1033 ↩︎

  2. https://github.com/dotnet/runtime/blob/9fb66db5ab5baae0269a0e5e2a79ee0e6f6b8f81/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs#L88-L96 ↩︎

  3. https://github.com/dotnet/runtime/blob/9fb66db5ab5baae0269a0e5e2a79ee0e6f6b8f81/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Unix.cs#L122-L181 ↩︎

  4. https://github.com/dotnet/runtime/blob/9fb66db5ab5baae0269a0e5e2a79ee0e6f6b8f81/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Rename.cs#L20-L21 ↩︎

  5. https://github.com/dotnet/runtime/blob/9fb66db5ab5baae0269a0e5e2a79ee0e6f6b8f81/src/libraries/Common/src/Interop/Unix/Interop.Libraries.cs#L11 ↩︎

  6. https://github.com/dotnet/runtime/blob/9fb66db5ab5baae0269a0e5e2a79ee0e6f6b8f81/src/native/libs/System.Native/pal_io.c ↩︎

GitHubで編集を提案

Discussion