DocSpace-buildtools/common/ASC.Common/Data/TempPath.cs

68 lines
1.7 KiB
C#
Raw Normal View History

2022-03-15 16:59:24 +00:00
namespace System.IO;
[Singletone]
public class TempPath
2021-05-21 13:26:42 +00:00
{
private readonly string _tempFolder;
public TempPath(IConfiguration configuration)
2021-05-21 13:26:42 +00:00
{
string rootFolder = AppContext.BaseDirectory;
if (string.IsNullOrEmpty(rootFolder))
2022-02-08 11:07:28 +00:00
{
rootFolder = Assembly.GetEntryAssembly().Location;
2022-02-08 11:07:28 +00:00
}
2021-05-21 13:26:42 +00:00
_tempFolder = configuration["temp"] ?? Path.Combine("..", "Data", "temp");
if (!Path.IsPathRooted(_tempFolder))
2022-02-08 11:07:28 +00:00
{
_tempFolder = Path.GetFullPath(Path.Combine(rootFolder, _tempFolder));
2022-02-08 11:07:28 +00:00
}
2021-05-21 13:26:42 +00:00
2022-02-08 11:07:28 +00:00
if (!Directory.Exists(_tempFolder))
{
Directory.CreateDirectory(_tempFolder);
}
}
2021-05-21 13:26:42 +00:00
2022-02-08 11:07:28 +00:00
public string GetTempPath()
{
return _tempFolder;
}
2021-05-21 13:26:42 +00:00
public string GetTempFileName()
{
FileStream f = null;
string path;
var count = 0;
2021-05-21 13:26:42 +00:00
do
2021-05-21 13:26:42 +00:00
{
path = Path.Combine(_tempFolder, Path.GetRandomFileName());
2021-05-21 13:26:42 +00:00
try
2021-05-21 13:26:42 +00:00
{
using (f = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read))
2021-05-21 13:26:42 +00:00
{
return path;
2021-05-21 13:26:42 +00:00
}
}
catch (IOException ex)
{
if (ex.HResult != -2147024816 || count++ > 65536)
2022-02-08 11:07:28 +00:00
{
throw;
2022-02-08 11:07:28 +00:00
}
}
catch (UnauthorizedAccessException ex)
{
if (count++ > 65536)
2022-02-08 11:07:28 +00:00
{
throw new IOException(ex.Message, ex);
2022-02-08 11:07:28 +00:00
}
}
} while (f == null);
2021-05-21 13:26:42 +00:00
return path;
2021-05-21 13:26:42 +00:00
}
2022-02-03 14:18:58 +00:00
}