59 lines
1.3 KiB
C#
59 lines
1.3 KiB
C#
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 異なる拡張子で新しい一時ファイルを作成します。
|
|
/// </summary>
|
|
/// <param name="extension"></param>
|
|
/// <returns></returns>
|
|
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);
|
|
}
|
|
}
|
|
}
|