By Pixy https://stackoverflow.com/questions/24396644/programmatically-mount-a-microsoft-virtual-hard-drive-vhd

This is an old question but it still has no answer so I'll provide one in case someone stumble upon it like I did.

Attaching the VHD

For the complete Reference on MSDN [VHD Reference]: http://msdn.microsoft.com/en-us/library/windows/desktop/dd323700(v=vs.85).aspx

OPEN_VIRTUAL_DISK_PARAMETERS openParameters;
openParameters.Version = OPEN_VIRTUAL_DISK_VERSION_1;
openParameters.Version1.RWDepth = OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT; VIRTUAL_STORAGE_TYPE storageType;
storageType.DeviceID = VIRTUAL_STORAGE_TYPE_DEVICE_VHD;
storageType.VendorId = VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; ATTACH_VIRTUAL_DISK_PARAMETERS attachParameters;
attachParameters.Version = ATTACH_VIRTUAL_DISK_VERSION_1; HANDLE vhdHandle; if (OpenVirtualDisk(&openStorageType, "{VHD PATH GOES HERE}",
VIRTUAL_DISK_ACCESS_ALL, OPEN_VIRTUAL_DISK_FLAG_NONE,
&openParameters, &vhdHandle) != ERROR_SUCCESS) {
// If return value of OpenVirtualDisk isn't ERROR_SUCCESS, there was a problem opening the VHD
} // Warning: AttachVirtualDisk requires elevation
if (AttachVirtualDisk(vhdHandle, , ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME,
, &attachParameters, ) != ERROR_SUCCESS) {
// If return value of AttachVirtualDisk isn't ERROR_SUCCESS, there was a problem attach the disk
}

VHD successfully attached, now it'll show up like any other physical disks and a drive letter will automatically be assigned to the volume(s) contained in the VHD. If you'd like to choose what drive letter is used to mount it, keep reading.

Assigning a drive letter

First, add the ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER flag to your AttachVirtualDisk call so it won't do this automatic letter assigning. Next, you'll have to find the volume path of the VHD volumes [it has this format: \\?\Volume{GUID}]:

wchar_t physicalDrive[MAX_PATH];
ULONG bufferSize = sizeof(physicalDrive);
GetVirtualDiskPhysicalPath(vhdHandle, &bufferSize, physicalDrive);

Now you'll have the physical path of your attached VHD in physical drive in the following format: \\.\PhysicalDrive# where # is the drive number you'll need to find your VHD volumes with FindFirstVolume/FindNextVolume. Extract the number and convert it to an integer and you'll be ready for the next piece of code:

char volumeName[MAX_PATH];
DWORD bytesReturned;
VOLUME_DISK_EXTENTS diskExtents;
HANDLE hFVol = FindFirstVolume(volumeName, sizeof(volumeName));
bool hadTrailingBackslash = false; do {
// I had a problem where CreateFile complained about the trailing \ and
// SetVolumeMountPoint desperately wanted the backslash there. I ended up
// doing this to get it working but I'm not a fan and I'd greatly
// appreciate it if someone has any further info on this matter
int backslashPos = strlen(volumeName) - ;
if (hadTrailingBackslash = volumeName[backslashPos] == '\\') {
volumeName[backslashPos] = ;
} HANDLE hVol = CreateFile(volumeName, , FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, , NULL);
if (hVol == INVALID_HANDLE_VALUE) {
return;
} DeviceIoControl(hVol, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
, &diskExtents, sizeof(diskExtents), &bytesReturned, NULL); // If the volume were to span across multiple physical disks, you'd find
// more than one Extents here but we don't have to worry about that with VHD
// Note that 'driveNumber' would be the integer you extracted out of
// 'physicalDrive' in the previous snippet
if (diskExtents.Extents[].DiskNumber == driveNumber) {
if (hadTrailingBackslash) {
volumeName[backslashPos] = '\\';
} // Found volume that's on the VHD, let's mount it with a letter of our choosing.
// Warning: SetVolumeMountPoint requires elevation
SetVolumeMountPoint("H:\\", volumeName);
}
} while (FindNextVolume(hFVol, volumeName, sizeof(volumeName)));
FindVolumeClose(hFVol);

Don't forget these includes and link to this library:

#define WINVER _WIN32_WINNT_WIN7
#include <windows.h>
#include <winioctl.h>
#include <virtdisk.h> #pragma comment(lib, "virtdisk.lib")

Disclaimer: This is something I was doing in a C# codebase, I translated the code to C/C++ because of the question but haven't tried to actually compile it. If you find errors in the code, please edit it or let me know so I can do it.

Edits: Typos, includes and lib, forgot FindVolumeClose, elevation warnings

Programmatically mount a Microsoft Virtual Hard Drive (VHD)的更多相关文章

  1. Microsoft Virtual Academy 介绍

    Microsoft Virtual Academy 是微软的虚拟学院,会推出微软各个方面的一些教程 介绍一点有用的链接 http://www.microsoftvirtualacademy.com/e ...

  2. (转)vmware下给linux虚拟机扩容

    “Well, here’s another fine mess you’ve gotten me into” Let us pretend that you have an Ubuntu Server ...

  3. How to Convert and Import VHD to VMDK (VMWare)

    VHD or Virtual Hard Disk is the disk image format used by Microsoft virtualization software such as ...

  4. VMWare File Format Learning && Use VHD File To Boot VMWare && CoreOS Docker Configuration And Running

    目录 . Virtual Machine Introduce . Vmware Image File Format . VHD File Format . Convert VHD File Into ...

  5. windows平台vhd磁盘文件挂载

    在windows平台下挂载vhd磁盘文件类似于挂载iso等文件; 使用VHDMount工具挂载VHD文件 启动Hyper-V里的外部VHD文件有点困难.如果在备份驱动上有个VHD文件,并需要从其虚拟机 ...

  6. DiskPart.exe and managing Virtual Hard Disks (VHDs) in Windows 7

    coreygoOctober 7, 2009 In Windows 7, new commands have been added in DiskPart to allow for the creat ...

  7. VHD轻松实现双系统

    VHD 是微软虚拟磁盘文件.   VHD(Microsoft Virtual Hard Disk format). 目前可以使用Microsoft Virtual PC 2007 and Micros ...

  8. VHD VHDX 区别

    A Virtual hard disk is saved either with VHD or VHDX file extension. VHD is the older while VHDX is ...

  9. MOUNT MACBOOK DISK (OSX / HFS+) ON UBUNTU 12.04 LTS WITH READ/WRITE

    MOUNT MACBOOK DISK (OSX / HFS+) ON UBUNTU 12.04 LTS WITH READ/WRITE So you want to mount your HFS+ ( ...

随机推荐

  1. Git之旅

    ithub安装,我选择的是windows下的版本. git配置用户信息 安装完成后,还需要最后一步设置,在命令行输入: $git config --global user.name "You ...

  2. NKOJ4238 天天爱跑步(【NOIP2016 DAY1】)

    问题描述 小C同学认为跑步非常有趣,于是决定制作一款叫做<天天爱跑步>的游戏.<天天爱跑步>是一个养成类游戏,需要玩家每天按时上线,完成打卡任务. 这个游戏的地图可以看作一棵包 ...

  3. WEB安全——XML注入

    浅析XML注入 认识XML DTD XML注入 XPath注入 XSL和XSLT注入 前言前段时间学习了.net,通过更改XML让连接数据库变得更方便,简单易懂,上手无压力,便对XML注入这块挺感兴趣 ...

  4. 使用IDEA创建SpringBoot项目

    SpringBoot学习第一步:搭建基础 IDEA对SpringBoot的项目支持可以说是点击就能完成基础的搭建,方便的不得了, 流程如下 1.左上角File选项,New project,选择Spri ...

  5. Centos8中安装JDK1.8

    在这里是通过yum命令进行安装的 安装前检查是否安装了jdk # java -version 如果使用 yum 安装的 jdk,请使用下面命令卸载 yum -y remove java-1.8.0-o ...

  6. 记录一次简单的springboot发送邮件功能

    场景:经常在我们系统中有通过邮件功能找回密码,或者发送生日祝福等功能,今天记录下springboot发送邮件的简单功能 1.引入maven <!-- 邮件开发--><dependen ...

  7. PTA数据结构与算法题目集(中文) 7-40奥运排行榜 (25 分)

    PTA数据结构与算法题目集(中文)  7-40奥运排行榜 (25 分) 7-40 奥运排行榜 (25 分)   每年奥运会各大媒体都会公布一个排行榜,但是细心的读者发现,不同国家的排行榜略有不同.比如 ...

  8. 搭建KVM

                                                                       系统&服务管理进阶 搭建KVM服务器 虚拟化概述 • vi ...

  9. VSCode设置大小写转换的快捷键

    本文已同步到专业技术网站 www.sufaith.com, 该网站专注于前后端开发技术与经验分享, 包含Web开发.Nodejs.Python.Linux.IT资讯等板块. VSCode在默认情况下没 ...

  10. std::forward和std::move

    std::forward完美转发 保证参数原来的属性(用在template的参数是引用的时候):左值引用在被转发之后仍然保持左值属性,右值引用在被转发之后依然保持右值属性 void show(int& ...