Skip to content

Instantly share code, notes, and snippets.

@bymyslf
Last active October 4, 2018 10:50
Show Gist options
  • Save bymyslf/7c71c7fc421ac1b367ff6ec8f7ef2c37 to your computer and use it in GitHub Desktop.
Save bymyslf/7c71c7fc421ac1b367ff6ec8f7ef2c37 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
public sealed class TempDirectory : IDisposable
{
private string _path;
public TempDirectory()
: this(System.IO.Path.GetTempFileName())
{
CreateDirectory();
}
public TempDirectory(string path)
{
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
_path = path;
}
public string Path
{
get
{
if (_path == null) throw new ArgumentNullException($"{GetType().Name} was disposed");
return _path;
}
}
private void CreateDirectory()
{
File.Delete(_path);
Directory.CreateDirectory(_path);
}
~TempDirectory()
=> Dispose(false);
public void Dispose()
=> Dispose(true);
private void Dispose(bool disposing)
{
if (disposing)
GC.SuppressFinalize(this);
if (_path != null)
{
try
{
Directory.Delete(_path, true);
}
catch { }
_path = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment