C# › File I/O & Streams

How would you implement a robust, atomic file-write operation that avoids leaving a corrupted or partially-written file if the process crashes mid-write?

Advanced

Answer

Write the new content to a TEMPORARY file first, then use File.Replace() (or File.Move() with overwrite) to atomically swap it into place as the final destination — since the OS-level rename/replace operation is atomic, readers never see a partially-written file, unlike directly overwriting the original file in place.
async Task SafeWriteAsync(string path, string content) {
  string tempPath = path + ".tmp";
  await File.WriteAllTextAsync(tempPath, content);
  File.Move(tempPath, path, overwrite: true); // atomic swap -- no partial-write window
}
Real-world example Safely updating a critical configuration or data file that other processes might read concurrently, without ever exposing a half-written state.

Common follow-ups: Why is directly calling File.WriteAllTextAsync() on the FINAL destination path risky for a process that might crash mid-write?