Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detected whether a hard drive is connected via USB?

I am trying to write a little backup program for friends and family and want it to be as simple to use a possible. I don't want to have to ask the user where to backup their data to, I just want to search for and use the first USB hard drive connected to the computer. Obtaining the unique ID of the hard drive would probably be a good idea too, just as a double check for next time the backup runs.

like image 262
Stacey Richards Avatar asked Sep 20 '25 11:09

Stacey Richards


1 Answers

I spent a little time looking around and found a function called SetupDiEnumDeviceInfo which did provide a solution to know whether a hard drive was removable or not but with that information I still can't (yet) map what I find back to a drive letter!

Here's what I have so far (following code creates a dll):

#include "stdafx.h"
#include <setupapi.h>
#include <devguid.h>
#include <cfgmgr32.h>
extern "C" __declspec(dllexport) int usb_hard_drives() {
  HDEVINFO hdevinfo = SetupDiGetClassDevs(&GUID_DEVCLASS_DISKDRIVE, NULL, NULL, DIGCF_PRESENT);
  if (hdevinfo == INVALID_HANDLE_VALUE) return -1;
  DWORD MemberIndex = 0;
  SP_DEVINFO_DATA sp_devinfo_data;
  ZeroMemory(&sp_devinfo_data, sizeof(sp_devinfo_data));
  sp_devinfo_data.cbSize = sizeof(sp_devinfo_data);
  int c = 0;
  while (SetupDiEnumDeviceInfo(hdevinfo, MemberIndex, &sp_devinfo_data)) {
    DWORD PropertyRegDataType;
    DWORD RequiredSize;
    DWORD PropertyBuffer;
    if (SetupDiGetDeviceRegistryProperty(hdevinfo, &sp_devinfo_data, SPDRP_CAPABILITIES, &PropertyRegDataType, (PBYTE)&PropertyBuffer, sizeof(PropertyBuffer), &RequiredSize)) {
      if (PropertyBuffer && CM_DEVCAP_REMOVABLE == CM_DEVCAP_REMOVABLE) {
        // do something here to identify the drive letter.
        c++;
      }
    }       
    MemberIndex++;
  }
  SetupDiDestroyDeviceInfoList(hdevinfo);
  return c;
}
like image 66
Stacey Richards Avatar answered Sep 23 '25 11:09

Stacey Richards