JD2022-TU1/main/tools/framework/JD.Core/TempFileManager.cs

131 lines
3.9 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
namespace JD.Core
{
public class TempFileManager : IDisposable
{
private readonly Dictionary<string, string> _tempFiles;
private int _untaggedIndex;
static TempFileManager()
{
Instance = new TempFileManager();
}
public static TempFileManager Instance { get; }
private TempFileManager()
{
_tempFiles = new Dictionary<string, string>();
_untaggedIndex = 0;
}
public void Dispose()
{
foreach (var file in _tempFiles)
{
File.Delete(file.Value);
}
}
public FileStream CreateAndOpenFile(string tag = null, string path = null, string subFolder = null, string fileNameWithoutExt = null, string extension = "")
{
if (String.IsNullOrEmpty(tag))
tag = GetUntaggedIdentifier();
if (path == null || !Directory.Exists(path))
path = Path.GetTempPath();
if (!path.EndsWith("\\"))
path += "\\";
Directory.CreateDirectory(path);
if (subFolder != null)
{
if (!subFolder.EndsWith("\\"))
subFolder += "\\";
path += subFolder;
Directory.CreateDirectory(path);
}
var forceNewFileCreation = true;
if (fileNameWithoutExt == null)
{
forceNewFileCreation = false;
fileNameWithoutExt = Guid.NewGuid().ToString();
while (File.Exists(path + fileNameWithoutExt + extension))
{
fileNameWithoutExt = Guid.NewGuid().ToString();
}
}
return CreateAndOpenFile(tag, path, fileNameWithoutExt, extension, forceNewFileCreation, 0);
}
private FileStream CreateAndOpenFile(string tag, string basePath, string fileNameWithoutExt, string extension, bool forceNewFileCreation, int shifter)
{
var path = basePath + fileNameWithoutExt;
if (shifter != 0)
path += $"_{shifter}";
path += extension;
if (_tempFiles.ContainsKey(tag))
{
try
{
if (_tempFiles[tag] == path)
return OpenFile(tag, FileMode.Create, FileAccess.ReadWrite);
else
return null;
}
catch (Exception)
{
return null;
}
}
try
{
var fileMode = forceNewFileCreation ? FileMode.Create : FileMode.CreateNew;
var fileStream = new FileStream(path, fileMode, FileAccess.ReadWrite);
_tempFiles.Add(tag, path);
return fileStream;
}
catch (Exception)
{
if (shifter > 10)
return null;
return CreateAndOpenFile(tag, basePath, fileNameWithoutExt, extension, forceNewFileCreation, ++shifter);
}
}
public FileStream OpenFile(string tag, FileMode fileMode, FileAccess fileAccess)
{
try
{
if (!_tempFiles.ContainsKey(tag))
return null;
return new FileStream(_tempFiles[tag], fileMode, fileAccess);
}
catch (Exception)
{
return null;
}
}
public string GetFileName(string tag)
{
if (!_tempFiles.ContainsKey(tag))
return null;
return _tempFiles[tag];
}
private string GetUntaggedIdentifier()
{
return $"_Untagged{_untaggedIndex++}";
}
}
}