---
title: "Temporary file to be automatically deleted after the program ends?"  
description: "Temporary file to be automatically deleted after the program ends?"  
author: "ICSM Computer"  
published: 2025-05-06  
updated: 2025-05-06  
canonical: https://www.mindstick.com/interview/34089/temporary-file-to-be-automatically-deleted-after-the-program-ends  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 2 minutes  

---

# Temporary file to be automatically deleted after the program ends?

To create a **temporary file that is automatically deleted** after your program ends, the best way in C# is to use a `FileStream` with `FileOptions.DeleteOnClose`. This ensures the file is removed when the stream is closed (even on crash, if handled correctly).

### Option 1: Auto-delete temp file using `FileStream` with `DeleteOnClose` (Windows only)

```plaintext
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".tmp");

        using (FileStream fs = new FileStream(
            tempPath,
            FileMode.Create,
            FileAccess.ReadWrite,
            FileShare.None,
            4096,
            FileOptions.DeleteOnClose)) // 👈 Key option
        {
            Console.WriteLine("Temp file created at: " + tempPath);
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Temporary content");
            fs.Write(data, 0, data.Length);
        }

        // At this point, the file is deleted
        Console.WriteLine("Temp file deleted automatically.");
    }
}
```

> `FileOptions.DeleteOnClose` works on **Windows** only. On Linux/macOS, you’ll need manual deletion.

### Option 2: Use `try-finally` to delete manually (cross-platform safe)

```plaintext
string tempFile = Path.GetTempFileName();

try
{
    File.WriteAllText(tempFile, "Temporary data");
    // Do your work
}
finally
{
    if (File.Exists(tempFile))
        File.Delete(tempFile); // Ensure cleanup
}
```

### Tip:

For truly cross-platform auto-cleanup, consider using a wrapper class with `IDisposable` that handles deletion in `Dispose()`.

## Answers

### Answer by ICSM Computer

To create a **temporary file that is automatically deleted** after your program ends, the best way in C# is to use a `FileStream` with `FileOptions.DeleteOnClose`. This ensures the file is removed when the stream is closed (even on crash, if handled correctly).

### Option 1: Auto-delete temp file using `FileStream` with `DeleteOnClose` (Windows only)

```plaintext
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".tmp");

        using (FileStream fs = new FileStream(
            tempPath,
            FileMode.Create,
            FileAccess.ReadWrite,
            FileShare.None,
            4096,
            FileOptions.DeleteOnClose)) // 👈 Key option
        {
            Console.WriteLine("Temp file created at: " + tempPath);
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Temporary content");
            fs.Write(data, 0, data.Length);
        }

        // At this point, the file is deleted
        Console.WriteLine("Temp file deleted automatically.");
    }
}
```

> `FileOptions.DeleteOnClose` works on **Windows** only. On Linux/macOS, you’ll need manual deletion.

### Option 2: Use `try-finally` to delete manually (cross-platform safe)

```plaintext
string tempFile = Path.GetTempFileName();

try
{
    File.WriteAllText(tempFile, "Temporary data");
    // Do your work
}
finally
{
    if (File.Exists(tempFile))
        File.Delete(tempFile); // Ensure cleanup
}
```

### Tip:

For truly cross-platform auto-cleanup, consider using a wrapper class with `IDisposable` that handles deletion in `Dispose()`.


---

Original Source: https://www.mindstick.com/interview/34089/temporary-file-to-be-automatically-deleted-after-the-program-ends

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
