Hungry Mind , Blog about everything in IT - C#, Java, C++, .NET, Windows, WinAPI, ...

How to detect VHD attached volume

In order to detect a volume is VHD attached, you can query its device descriptor using DeviceIoControl:

#include <windows.h>
#include <iostream>
 
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
   if (argc < 2) {
      cerr << "Usage: FsUtil.exe file" << endl;
      return -1;
   }
   auto const h = ::CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
   if (h == INVALID_HANDLE_VALUE) {
      cerr << "Unable to open " << argv[1] << endl;
      return -2;
   }
 
   STORAGE_PROPERTY_QUERY spq = { StorageDeviceProperty, PropertyStandardQuery };
 
   unsigned char b[1024];
   auto const btyped = reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR *>(&b[0]);
 
   DWORD br;
   if (::DeviceIoControl(h, IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), &b[0], sizeof(b), &br, nullptr) == FALSE) {
      cerr << "DeviceIoControl failed with " << ::GetLastError() << endl;
      return -3;
   }
 
   auto const vendor = reinterpret_cast<LPCSTR>(b + btyped->VendorIdOffset);
   auto const product = reinterpret_cast<LPCSTR>(b + btyped->ProductIdOffset);
 
   cout << "Bus type: " << btyped->BusType << endl
        << "Vendor: " << vendor << endl
        << "Product: " << product << endl;
 
   return 0;
}

BusType would be BusTypeFileBackedVirtual, vendor - Msft, product - Virtual Disk.

Copyright 2007-2011 Chabster