wabbajack/Wabbajack.Paths.IO/TemporaryFileManager.cs

78 lines
1.9 KiB
C#
Raw Normal View History

2021-09-27 12:42:46 +00:00
using System;
using System.IO;
using System.Threading;
2022-10-07 21:02:16 +00:00
using System.Threading.Tasks;
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
namespace Wabbajack.Paths.IO;
2022-10-07 21:02:16 +00:00
public class TemporaryFileManager : IDisposable, IAsyncDisposable
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
private readonly AbsolutePath _basePath;
private readonly bool _deleteOnDispose;
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public TemporaryFileManager() : this(KnownFolders.EntryPoint.Combine("temp"))
{
}
2021-09-27 12:42:46 +00:00
public TemporaryFileManager(AbsolutePath basePath, bool deleteOnDispose = true)
2021-10-23 16:51:17 +00:00
{
_deleteOnDispose = deleteOnDispose;
2021-10-23 16:51:17 +00:00
_basePath = basePath;
_basePath.CreateDirectory();
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public void Dispose()
{
if (!_deleteOnDispose) return;
2021-10-23 16:51:17 +00:00
for (var retries = 0; retries < 10; retries++)
2022-10-07 21:02:16 +00:00
{
2021-10-23 16:51:17 +00:00
try
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
if (!_basePath.DirectoryExists())
2021-09-27 12:42:46 +00:00
return;
2021-10-23 16:51:17 +00:00
_basePath.DeleteDirectory();
return;
2021-09-27 12:42:46 +00:00
}
2022-10-07 21:02:16 +00:00
catch (IOException)
2021-10-23 16:51:17 +00:00
{
Thread.Sleep(1000);
}
2022-10-07 21:02:16 +00:00
}
}
public async ValueTask DisposeAsync()
{
if (!_deleteOnDispose) return;
for (var retries = 0; retries < 10; retries++)
{
try
{
if (!_basePath.DirectoryExists())
return;
_basePath.DeleteDirectory();
return;
}
catch (IOException)
{
await Task.Delay(1000);
}
}
2021-10-23 16:51:17 +00:00
}
2021-09-27 12:42:46 +00:00
public TemporaryPath CreateFile(Extension? ext = default, bool deleteOnDispose = true)
2021-10-23 16:51:17 +00:00
{
var path = _basePath.Combine(Guid.NewGuid().ToString());
if (path.Extension != default)
path = path.WithExtension(ext);
return new TemporaryPath(path);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public TemporaryPath CreateFolder()
{
var path = _basePath.Combine(Guid.NewGuid().ToString());
path.CreateDirectory();
return new TemporaryPath(path);
2021-09-27 12:42:46 +00:00
}
2022-10-07 21:02:16 +00:00
2021-09-27 12:42:46 +00:00
}