Skip to content

Instantly share code, notes, and snippets.

@poulfoged
Created September 8, 2015 08:05
Show Gist options
  • Save poulfoged/c9c0c4c32100cabbce5f to your computer and use it in GitHub Desktop.
Save poulfoged/c9c0c4c32100cabbce5f to your computer and use it in GitHub Desktop.
internal class TemporaryFile : IDisposable
{
private readonly FileInfo _fileInfo;
private bool _disposed;
public TemporaryFile(string extension = "tmp")
{
_fileInfo = CreateFilename(extension);
}
private static FileInfo CreateFilename(string extension)
{
return new FileInfo(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + "." + extension));
}
private TemporaryFile(FileInfo file)
{
_fileInfo = file;
}
public static async Task<TemporaryFile> Create(Stream stream, string extension = "tmp")
{
var file = CreateFilename(extension);
using (stream)
using (var destination = file.OpenWrite())
await stream.CopyToAsync(destination);
return new TemporaryFile(file);
}
public TemporaryFile(Stream stream, string extension = "tmp")
: this(extension)
{
using (stream)
using (var destination = _fileInfo.OpenWrite())
stream.CopyTo(destination);
}
public FileInfo Info
{
get { return _fileInfo; }
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
try
{
_fileInfo.Delete();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
_disposed = true;
}
~TemporaryFile()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public async Task CopyTo(Stream result)
{
using (var stream = _fileInfo.OpenRead())
await stream.CopyToAsync(result);
if (result.CanSeek)
result.Seek(0, SeekOrigin.Begin);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment