Introduction
In this article, I'll introduce a small class which you can use to write strings or binary data to a temporary file and have the file automatically deleted again after using it. So in short, you can do the following steps with the class:
- Create a temporary file on disk with the content of a string (or binary object) in memory
- Perform operations on/with the temporary file
- Delete the temporary file from disk
This article is a follow-up to my article "A small C# File Cloner class".
Background
I came up with the class as I was using some third party library that required a file with data as a parameter, but I had the data in memory only (in a string
class).
Instead of manually creating the file, writing the file to disk, passing it to the function, and then manually cleaning up the file again (and be aware of possible exceptions), I wanted to have a dead simple solution. I hope this one is such a solution.
So I created a class that implements the IDisposable interface, creates a temporary file with the in-memory data in its constructor, and deletes the temporary file again in its destructor or via the IDisposable.Dispose method.
Using the Code
Writing to Files
Using the code should be really simple. Just create an instance of the ZetaTemporaryFileCreator
class inside a using
directive, passing the data to write to the file in the constructor:
using ( var tfc = new ZetaTemporaryFileCreator( "Some text to write to the file." ) )
{
myFunctionThatOperatesOnAFileRatherThanOnInMemoryData( tfc.FilePath );
}
The using
block ensures that the temporary file is being deleted again, even in case of an exception occurring.
Reading from Files
You can also use the code for functions that write to a file and you want to read the results back into memory later.
Use the parameterless constructor together with one (or both) of the properties FileContentString
and FileContentBinary
:
using ( var tfc = new ZetaTemporaryFileCreator() )
{
myFunctionThatWritesDataToAFileRatherThanIntoMemory( tfc.FilePath );
myFunctionThatOperatesOnInMemoryData( tfc.FileContentString );
}
Again, the using
block ensures that the temporary file is being deleted again, even in case of an exception occurring.
Points of Interest
In this article, I've shown you a really small class which allows for automatic creation and removal of a temporary file. The download contains the complete C# class which you can simply drop into your own projects.
For your questions, comments and feedback (which I really love to get!), please use the comments section below at the bottom of this article. Thank you!
History
- 2010-09-12 - Added parameterless constructor and the properties
FileContentString
and FileContentBinary
to read back from file into memory
- 2010-09-06 - First release to CodeProject.com