---
title: "How do you perform transactional file writes (e.g., write to a temp file, then replace original)?"  
description: "How do you perform transactional file writes (e.g., write to a temp file, then replace original)?"  
author: "ICSM Computer"  
published: 2025-05-12  
updated: 2025-05-27  
canonical: https://www.mindstick.com/forum/161605/how-do-you-perform-transactional-file-writes-e-g-write-to-a-temp-file-then-replace-original  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 2 minutes  

---

# How do you perform transactional file writes (e.g., write to a temp file, then replace original)?

How do you perform transactional [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) writes (e.g., write to a temp file, then [replace](https://yourviews.mindstick.com/view/81330/cow-antibody-research-in-usa-a-step-ahead-to-replace-plasma-therapy) original)?

## Replies

### Reply by Anubhav Sharma

To perform **transactional file writes** in C#, the safest pattern is to:

- **Write to a temporary file**
- **Flush and close it**
- **Replace the original file with the temp file** (atomically)

This ensures the original file remains intact in case of crashes or write errors.

## Example: Transactional Write

```cs
using System;
using System.IO;

public class SafeFileWriter
{
    public static void WriteTransactional(string filePath, string content)
    {
        string tempFile = Path.GetTempFileName();

        try
        {
            // Write to temp file
            File.WriteAllText(tempFile, content);

            // Ensure temp file is flushed and closed
            File.SetAttributes(tempFile, FileAttributes.Normal);

            // Replace original file atomically
            File.Replace(tempFile, filePath, null, ignoreMetadataErrors: true);
        }
        catch
        {
            // Optional: clean up temp file if something goes wrong
            if (File.Exists(tempFile))
                File.Delete(tempFile);

            throw;
        }
    }
}
```

## Usage

```cs
SafeFileWriter.WriteTransactional("config.ini", "Safe=Write\nEnabled=True");
```

## Notes

| Aspect | Detail |
| --- | --- |
| `Path.GetTempFileName()` | Creates a secure temp file in the system temp folder |
| `File.Replace()` | Atomically replaces target file (only works on NTFS / Windows) |
| `ignoreMetadataErrors: true` | Ignores errors when copying attributes (like timestamps) |
| Cross-platform? | For Linux/macOS, manually delete and move temp file (see below) |

## Alternative for Non-Windows Platforms

If you're not on Windows (e.g., using Linux/macOS), `File.Replace` isn't supported. Use:

```plaintext
File.Delete(originalPath);             // Optional: ensure it's gone
File.Move(tempFilePath, originalPath); // Non-atomic
```

To reduce risk of failure:

1. Use `FileStream` with proper `Flush()` and `Close()`
2. Place temp file in the **same directory** as target file to reduce cross-volume issues.


---

Original Source: https://www.mindstick.com/forum/161605/how-do-you-perform-transactional-file-writes-e-g-write-to-a-temp-file-then-replace-original

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
