c# – How to check if a disk is sleeping?

Question:

If Windows automatically turns off disks when inactive, then how to programmatically check if the disk is sleeping or turned on, of course, without waking it up?

Answer:

In this way, we managed to check the PowerState of the disk and did not wake it up at the same time. My home system is very quiet and the disc starts and stops clearly audible. More solid proof: after repeated launches, the state does not change, in contrast to the option with receiving a handle from a file.

True, not without a fly in the ointment, administrator rights are required and you need to know the serial number of the checked physical disk in the system.

99% of the code is examples with PInvoke, my only layout is in a working version.

void Main()
{
    String status = String.Empty;
    bool fOn = false;
    var driveX = 1;
    var hFile = CreateFileW($@"\\.\PHYSICALDRIVE{driveX}", FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, FileAttributes.Offline, IntPtr.Zero);
    bool result = GetDevicePowerState(hFile, out fOn);
    if (result)
    {
        if (fOn)
        {
            status = "Disk is powered up and spinning";
        }
        else
        {
            status = "Disk is sleeping";
        }
    }
    else
    {
        status = "Cannot get Disk Status";
    }
    Console.WriteLine(status);

}

//https://www.pinvoke.net/default.aspx/kernel32.CreateFile
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr CreateFileW(
     [MarshalAs(UnmanagedType.LPWStr)] string filename,
     [MarshalAs(UnmanagedType.U4)] FileAccess access,
     [MarshalAs(UnmanagedType.U4)] FileShare share,
     IntPtr securityAttributes,
     [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
     [MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes,
     IntPtr templateFile);

//https://www.pinvoke.net/default.aspx/kernel32.GetDevicePowerState
[DllImport("kernel32.dll")]
static extern bool GetDevicePowerState(IntPtr hDevice, out bool pfOn);

Restrictions:

  • the system disk sleeps only when the whole system is sleeping (at least on Windows).
  • the check does not make sense if there is only one physical disk in the system, it will be active anyway if the whole system is awake (see above).
  • I'm not sure about SSD and other removable media, there was nothing to check on, the system lives on the only SDD and it never sleeps.
Scroll to Top