Introduction
This article shows you a small class that you can use in various projects to simplify the following process:
- Create a temporary copy of a file.
- Perform operations on/with the temporary file.
- Delete the temporary copy of the file.
Background
I created the class for a web application project where I read some Microsoft Excel documents into memory, manipulated the Excel documents in memory and finally sent them to the user's web browser.
Usually this task is as easy as doing some File operations and get a Stream object to the file. This works great when the file is not opened in Microsoft Excel. When it is opened, it is exclusively locked by Excel, resulting in exceptions in my code when I try to access the file stream.
What still works is to copy the file.
So I created a class that implements the IDisposable interface, creates a temporary copy of the file in its constructor, and deletes the temporary file again in its destructor or via the IDisposable.Dispose method.
Using the Code
Using the code is really simple. Instead of writing something like:
myFunctionThatOperatesOnTheFile( @"C:\Some\Path\File.xlsx" );
You write a code like:
using ( var tfc = new ZetaTemporaryFileCloner( @"C:\Some\Path\File.xlsx" ) )
{
myFunctionThatOperatesOnTheFile( tfc.FilePath );
}
Easy, isn't it?
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 love to get!), please use the comments section below at the bottom of this article. Thank you!
History