c# – How to check if a drive 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 not wake it up at the same time. My home system is very quiet and I can clearly hear the drive starting and stopping. More weighty evidence: the state does not change during repeated launches, in contrast to the option with obtaining 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 physical disk being checked in the system.

99% of the code examples are with PInvoke, mine is just linking to 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 sleeps (at least on Windows).
  • the check does not make sense if the physical disk in the system is the only one, it will be active anyway if the whole system is not sleeping (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