How do you perform transactional file writes (e.g., write to a temp file, then replace original)?
home / developersection / forums / how do you perform transactional file writes (e.g., write to a temp file, then replace original)?
How do you perform transactional file writes (e.g., write to a temp file, then replace original)?
Anubhav Kumar
27-May-2025To perform transactional file writes in C#, the safest pattern is to:
This ensures the original file remains intact in case of crashes or write errors.
Example: Transactional Write
Usage
Notes
Path.GetTempFileName()File.Replace()ignoreMetadataErrors: trueAlternative for Non-Windows Platforms
If you're not on Windows (e.g., using Linux/macOS),
File.Replaceisn't supported. Use:To reduce risk of failure:
FileStreamwith properFlush()andClose()