Wednesday, June 5, 2013

Sasa.IO.DisposableFile - Simple Temporary File Handling

This is the twenty first post in my ongoing series covering the abstractions in Sasa. Previous posts:

Sasa.IO.DisposableFile is a simple object intended to automate the handling of temporary files. Like most IDisposable objects, a DisposableFile is intended to be used within a "using" block, and the file it references is deleted upon exiting the block:

using (var tmp = new DisposableFile(true, "foo.txt"))
{
    File.WriteAllText(tmp.Path, "hello world!");
    Console.WriteLine(File.ReadAllText(tmp.Path));
}
Console.WriteLine(File.Exists("foo.txt"));
     
// output:
// hello world!
// false

Any FileNotFoundException's thrown on dispose are ignored, so you can safely move the file within the "using" block.

Sasa.IO.DisposableFile Constructor

The DisposableFile constructor creates a temporary file:

using (var tmp = new DisposableFile(createIfNotExists: true,
                                    path: "foo.txt"))
{
    ...
}

Sasa.IO.DisposableFile.Path

The Path property exposes the path to the disposable file:

using (var tmp = new DisposableFile(createIfNotExists: true,
                                    path: "foo.txt"))
{
    Console.WriteLine(tmp.Path);
}
// output:
// foo.txt

Sasa.IO.DisposableFile.CreateTemporary

The CreateTemporary static method invokes System.IO.Path.GetTempFileName and returns a DisposableFile instance encapsulating the created file:

using (var tmp = DisposableFile.CreateTemporary())
{
    File.WriteAllText(tmp.Path, "hello world!");
}

No comments: