wabbajack/Wabbajack.Common/Util/TempFile.cs

58 lines
1.6 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;
2020-03-26 23:02:15 +00:00
using AlphaPath = Alphaleonis.Win32.Filesystem.Path;
namespace Wabbajack.Common
{
public class TempFile : IAsyncDisposable
{
public FileInfo File { get; private set; }
2020-03-26 23:02:15 +00:00
public AbsolutePath Path => (AbsolutePath)File.FullName;
public bool DeleteAfter = true;
public TempFile(bool deleteAfter = true, bool createFolder = true)
2020-04-03 03:57:59 +00:00
: this(new FileInfo((string)GetTempFilePath()))
{
}
public TempFile(AbsolutePath path, bool deleteAfter = true, bool createFolder = true)
: this(new FileInfo((string)path))
{
}
2020-04-03 03:57:59 +00:00
private static AbsolutePath GetTempFilePath()
{
2020-04-03 20:19:10 +00:00
var path = (@"temp\" + Guid.NewGuid()).RelativeTo(AbsolutePath.EntryPoint).WithExtension(Consts.TempExtension);
2020-04-03 03:57:59 +00:00
path.Parent.CreateDirectory();
return path;
}
public TempFile(FileInfo file, bool deleteAfter = true, bool createFolder = true)
{
this.File = file;
2020-12-31 23:39:18 +00:00
if (createFolder && file.Directory != null && !file.Directory!.Exists)
{
file.Directory.Create();
}
this.DeleteAfter = deleteAfter;
}
public TempFile(Extension ext)
:this(new FileInfo((string)GetTempFilePath().WithExtension(ext)))
{
}
public async ValueTask DisposeAsync()
{
2020-08-12 22:23:02 +00:00
if (DeleteAfter && Path.Exists)
{
await Path.DeleteAsync();
}
}
}
}