I've also had the same requirement before, and I've created a small class to solve it:
public sealed class TemporaryFile : IDisposable {
public TemporaryFile() :
this(Path.GetTempPath()) { }
public TemporaryFile(string directory) {
Create(Path.Combine(directory, Path.GetRandomFileName()));
}
~TemporaryFile() {
Delete();
}
public void Dispose() {
Delete();
GC.SuppressFinalize(this);
}
public string FilePath { get; private set; }
private void Create(string path) {
FilePath = path;
using (File.Create(FilePath)) { };
}
private void Delete() {
if (FilePath == null) return;
File.Delete(FilePath);
FilePath = null;
}
}
It creates a temporary file in a folder you specify or in the system temporary folder. It's a disposable class, so at the end of its life (either Dispose
or the destructor), it deletes the file. You get the name of the file created (and path) through the FilePath
property. You can certainly extend it to also open the file for writing and return its associated FileStream
.
An example usage:
using (var tempFile = new TemporaryFile()) {
// use the file through tempFile.FilePath...
}