Move temp file gen for File.Replace to separate file

This commit is contained in:
Soreepeong 2024-06-05 00:29:15 +09:00
parent e144956a48
commit 729795ff9e
2 changed files with 25 additions and 1 deletions

View file

@ -90,7 +90,7 @@ internal sealed partial class TextureManager
throw new NullReferenceException($"{nameof(path)} cannot be null."); throw new NullReferenceException($"{nameof(path)} cannot be null.");
using var wrapAux = new WrapAux(wrap, true); using var wrapAux = new WrapAux(wrap, true);
var pathTemp = $"{path}.{GetCurrentThreadId():X08}{Environment.TickCount64:X16}.tmp"; var pathTemp = Util.GetTempFileNameForFileReplacement(path);
var trashfire = new List<Exception>(); var trashfire = new List<Exception>();
try try
{ {

View file

@ -640,6 +640,30 @@ public static class Util
throw new Win32Exception(); throw new Win32Exception();
} }
/// <summary>Gets a temporary file name, for use as the sourceFileName in
/// <see cref="File.Replace(string,string,string?)"/>.</summary>
/// <param name="targetFile">The target file.</param>
/// <returns>A temporary file name that should be usable with <see cref="File.Replace(string,string,string?)"/>.
/// </returns>
/// <remarks>No write operation is done on the filesystem.</remarks>
public static string GetTempFileNameForFileReplacement(string targetFile)
{
Span<byte> buf = stackalloc byte[9];
Random.Shared.NextBytes(buf);
for (var i = 0; ; i++)
{
var tempName =
Path.GetFileName(targetFile) +
Convert.ToBase64String(buf)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
var tempPath = Path.Join(Path.GetDirectoryName(targetFile), tempName);
if (i >= 64 || !Path.Exists(tempPath))
return tempPath;
}
}
/// <summary> /// <summary>
/// Gets a random, inoffensive, human-friendly string. /// Gets a random, inoffensive, human-friendly string.
/// </summary> /// </summary>