Files
SongTidy/SongTidy.Tests/TestUtilities/TempDirectory.cs
T

40 lines
1.4 KiB
C#
Raw Normal View History

2026-10-22 21:24:13 +08:00
namespace SongTidy.Tests.TestUtilities;
/// <summary>
/// Creates a unique temporary directory per test instance and removes it on disposal.
/// </summary>
public sealed class TempDirectory : IDisposable {
/// <summary>
/// Gets the unique directory path managed by this instance.
/// </summary>
public string FullPath { get; }
/// <summary>
/// Creates a unique temporary directory.
/// </summary>
public TempDirectory() {
FullPath = Path.Combine(Path.GetTempPath(), "songtidy-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(FullPath);
}
/// <summary>
/// Deletes the directory tree, retrying once after a short delay.
/// </summary>
public void Dispose() {
try {
// SAFETY: Recursive deletion is confined to the GUID-named directory
// created by this instance under the OS temp folder.
Directory.Delete(FullPath, recursive: true);
} catch (IOException) {
// A file handle may still be closing; retry once before giving up.
Thread.Sleep(100);
try {
// SAFETY: The retry targets the same instance-owned temp directory.
Directory.Delete(FullPath, recursive: true);
} catch (IOException) {
// Leftovers in the OS temp folder are harmless; never fail a test over cleanup.
}
}
}
}