diff --git a/LibreHardwareMonitorLib/Hardware/Storage/WindowsStorage.cs b/LibreHardwareMonitorLib/Hardware/Storage/WindowsStorage.cs index 378acde..a3a4070 100644 --- a/LibreHardwareMonitorLib/Hardware/Storage/WindowsStorage.cs +++ b/LibreHardwareMonitorLib/Hardware/Storage/WindowsStorage.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.Management; using System.Runtime.InteropServices; +using System.Text; using LibreHardwareMonitor.Interop; namespace LibreHardwareMonitor.Hardware.Storage; @@ -16,10 +17,15 @@ internal static class WindowsStorage public static Storage.StorageInfo GetStorageInfo(string deviceId, uint driveIndex) { using SafeHandle handle = Kernel32.OpenDevice(deviceId); + if (handle?.IsInvalid != false) return null; - var query = new Kernel32.STORAGE_PROPERTY_QUERY { PropertyId = Kernel32.STORAGE_PROPERTY_ID.StorageDeviceProperty, QueryType = Kernel32.STORAGE_QUERY_TYPE.PropertyStandardQuery }; + var query = new Kernel32.STORAGE_PROPERTY_QUERY + { + PropertyId = Kernel32.STORAGE_PROPERTY_ID.StorageDeviceProperty, + QueryType = Kernel32.STORAGE_QUERY_TYPE.PropertyStandardQuery + }; if (!Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_STORAGE_QUERY_PROPERTY, @@ -34,12 +40,12 @@ internal static class WindowsStorage } IntPtr descriptorPtr = Marshal.AllocHGlobal((int)header.Size); + try { - if (!Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_STORAGE_QUERY_PROPERTY, ref query, Marshal.SizeOf(query), descriptorPtr, header.Size, out _, IntPtr.Zero)) - return null; - - return new StorageInfo((int)driveIndex, descriptorPtr); + return Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_STORAGE_QUERY_PROPERTY, ref query, Marshal.SizeOf(query), descriptorPtr, header.Size, out uint bytesReturned, IntPtr.Zero) + ? new StorageInfo((int)driveIndex, descriptorPtr) + : null; } finally { @@ -54,6 +60,7 @@ internal static class WindowsStorage try { using var s = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskPartition " + "WHERE DiskIndex = " + driveIndex); + foreach (ManagementBaseObject o in s.Get()) { if (o is ManagementObject dp) @@ -91,7 +98,7 @@ internal static class WindowsStorage private static string GetString(IntPtr descriptorPtr, uint offset) { - return offset > 0 ? Marshal.PtrToStringAnsi(new IntPtr(descriptorPtr.ToInt64() + offset))?.Trim() : string.Empty; + return offset > 0 ? Marshal.PtrToStringAnsi(IntPtr.Add(descriptorPtr, (int)offset))?.Trim() : string.Empty; } } }