Fork me on GitHub

Temporary File Holder

Motivation

Cleaning-up temporary files can be tedious.

The TemporaryFileHolder allows you to create a temporary file by specifying its content. When the temporary file holder is disposed, the file is deleted.

Usage

1
2
3
4
5
6
Stream content = ...
 
using (var holder = new TemporaryFileHolder("c:\\folder\\filename.extension", content))
{
    // do something interesting
}

You can specify the absolute file path of the temporary file to create and its content - either with a stream or a string.

To delete the temporary file, dispose the temporary file holder.

Inside a Unit Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[TestFixture]
public class Test
{
    TemporaryFileHolder temporaryFileHolder;
     
    [SetUp]
    public void SetUp()
    {
        temporaryFileHolder = new TemporaryFileHolder(
            "c:\\temp\\file.ext",
            "this is the content");
    }
     
    [TearDown]
    public void TearDown()
    {
        temporaryFileHolder.Dispose();
    }
}

Use the SetUp method (NUnit), the constructor (xUnit) or Establish (MSpec) to create the file.

Use the TearDown method (NUnit), destructor (xUnit) or CleanUp (MSpec) to delete the file.

Limitations

When the file cannot be deleted upon disposal of the temporary file holder, the file will stay and the occurred exception is swallowed.

Back to Top