wabbajack/Wabbajack.Paths.IO/TemporaryFileManager.cs

54 lines
1.4 KiB
C#
Raw Normal View History

2021-09-27 12:42:46 +00:00
using System;
using System.IO;
using System.Threading;
2021-10-23 16:51:17 +00:00
namespace Wabbajack.Paths.IO;
public class TemporaryFileManager : IDisposable
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++)
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
}
2021-10-23 16:51:17 +00:00
catch (IOException ex)
{
Thread.Sleep(1000);
}
}
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
}
}