Redone handling of windows compactor handling.

This commit is contained in:
cake
2025-10-29 04:43:18 +01:00
parent 177534d78b
commit 9a846a37d4

View File

@@ -372,6 +372,22 @@ public sealed class FileCompactor : IDisposable
return _clusterSizes[root]; return _clusterSizes[root];
} }
public static bool UseSafeHandle(SafeHandle handle, Func<IntPtr, bool> action)
{
bool addedRef = false;
try
{
handle.DangerousAddRef(ref addedRef);
IntPtr ptr = handle.DangerousGetHandle();
return action(ptr);
}
finally
{
if (addedRef)
handle.DangerousRelease();
}
}
private static bool IsWOFCompactedFile(string filePath) private static bool IsWOFCompactedFile(string filePath)
{ {
uint buf = 8; uint buf = 8;
@@ -424,22 +440,25 @@ public sealed class FileCompactor : IDisposable
ulong length = (ulong)Marshal.SizeOf(_efInfo); ulong length = (ulong)Marshal.SizeOf(_efInfo);
try try
{ {
using var fs = new FileStream(path, FileMode.Open); using var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
#pragma warning disable S3869 // "SafeHandle.DangerousGetHandle" should not be called var handle = fs.SafeFileHandle;
var hFile = fs.SafeFileHandle.DangerousGetHandle();
#pragma warning restore S3869 // "SafeHandle.DangerousGetHandle" should not be called if (handle.IsInvalid)
if (fs.SafeFileHandle.IsInvalid)
{ {
_logger.LogWarning("Invalid file handle to {file}", path); _logger.LogWarning("Invalid file handle to {file}", path);
return false; return false;
} }
var ret = WofSetFileDataLocation(hFile, WOF_PROVIDER_FILE, efInfoPtr, length); return UseSafeHandle(handle, hFile =>
if (!(ret == 0 || ret == unchecked((int)0x80070158)))
{ {
_logger.LogWarning("Failed to compact {file}: {ret}", path, ret.ToString("X")); int ret = WofSetFileDataLocation(hFile, WOF_PROVIDER_FILE, efInfoPtr, length);
return false; if (ret != 0 && ret != unchecked((int)0x80070158))
} {
_logger.LogWarning("Failed to compact {file}: {ret}", path, ret.ToString("X"));
return false;
}
return true;
});
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -450,7 +469,6 @@ public sealed class FileCompactor : IDisposable
{ {
Marshal.FreeHGlobal(efInfoPtr); Marshal.FreeHGlobal(efInfoPtr);
} }
return true;
} }
private bool BtrfsCompressFile(string path) private bool BtrfsCompressFile(string path)