wabbajack/Wabbajack.Common/Util/TempFolder.cs

60 lines
1.5 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wabbajack.Common
{
public class TempFolder : IAsyncDisposable
{
2020-03-23 12:57:18 +00:00
public AbsolutePath Dir { get; }
public bool DeleteAfter = true;
private static Task _cleanTask;
static TempFolder()
{
_cleanTask = Task.Run(() => "tmp_files".RelativeTo(AbsolutePath.EntryPoint).DeleteDirectory());
}
public static void Init()
{
// Nothing to do, as work is done in static ctor
}
private TempFolder(bool deleteAfter = true)
{
Dir = Path.Combine("tmp_files", Guid.NewGuid().ToString()).RelativeTo(AbsolutePath.EntryPoint);
2020-03-23 12:57:18 +00:00
if (!Dir.Exists)
Dir.CreateDirectory();
DeleteAfter = deleteAfter;
}
public static async Task<TempFolder> Create(bool deleteAfter = true)
{
await _cleanTask;
return new TempFolder(deleteAfter: deleteAfter);
}
2020-03-23 12:57:18 +00:00
public TempFolder(AbsolutePath dir, bool deleteAfter = true)
{
2020-03-23 12:57:18 +00:00
Dir = dir;
if (!dir.Exists)
{
2020-03-23 12:57:18 +00:00
Dir.Create();
}
2020-03-23 12:57:18 +00:00
DeleteAfter = deleteAfter;
}
public async ValueTask DisposeAsync()
{
Utils.Log($"Deleting {Dir}");
2020-03-23 12:57:18 +00:00
if (DeleteAfter && Dir.Exists)
{
await Utils.DeleteDirectory(Dir);
}
}
}
}