Atomic file write
Writes through a temporary file and replaces the destination only after the write succeeds.
View code
public static void WriteAllTextAtomic(string path, string content, Encoding? encoding = null)
{
encoding ??= new UTF8Encoding(false);
var fullPath = Path.GetFullPath(path);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
var tempPath = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
File.WriteAllText(tempPath, content, encoding);
File.Move(tempPath, fullPath, true);
}
finally
{
if (File.Exists(tempPath)) File.Delete(tempPath);
}
}