47 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			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 (FilePath == null) return;
 | 
						|
            File.Delete(FilePath);
 | 
						|
            FilePath = null;
 | 
						|
        }
 | 
						|
    }
 | 
						|
}
 |