namespace ReviewProxy.Lib.IO; public class TempFile : IDisposable { public string FilePath { get; } private FileStream? stream; public TempFile() { // 一時フォルダが提供されている場合、一時フォルダからファイルを取得する string tmpPath = Path.GetTempPath(); if (!Directory.Exists(tmpPath)) { FilePath = Path.GetTempFileName(); } else { FilePath = Path.Combine(tmpPath, $"{Guid.NewGuid().ToString()}.tmp"); } stream = null; } private TempFile(string filePath) { FilePath = filePath; stream = null; } /// /// 異なる拡張子で新しい一時ファイルを作成します。 /// /// /// public TempFile ChangeFileExtension(string extension) { return new TempFile(Path.ChangeExtension(FilePath, extension)); } public FileStream Open() { if (stream is null) { stream = new FileStream(FilePath, FileMode.OpenOrCreate); } return stream; } public void Dispose() { stream?.Dispose(); if (File.Exists(FilePath)) { File.Delete(FilePath); } } }