Files
elwig/Elwig/Helpers/TempFile.cs
T
lorenz.stechauner 2cc58f8df6
Test / Run tests (push) Successful in 2m29s
Elwig: Fix most compiler warnings
2026-11-24 19:37:13 +01:00

47 lines
1.1 KiB
C#

using System;
using System.IO;
namespace Elwig.Helpers {
public sealed class TempFile : IDisposable {
private int Usages = 0;
public string FilePath { get; private set; }
public string FileName => Path.GetFileName(FilePath);
public TempFile() : this(null) { }
public TempFile(string? ext) : this(App.TempPath, ext) { }
public TempFile(string dir, string? ext) {
FilePath = Path.Combine(dir, Path.GetRandomFileName().Replace(".", "") + (ext != null ? $".{ext}" : ""));
Usages++;
Create();
}
~TempFile() {
Delete();
}
public void Dispose() {
if (--Usages == 0) {
Delete();
GC.SuppressFinalize(this);
}
}
public TempFile NewReference() {
Usages++;
return this;
}
private void Create() {
using (File.Create(FilePath)) { };
}
private void Delete() {
if (Usages < 0) return;
File.Delete(FilePath);
Usages = -1;
}
}
}