使用 DiskPart 对 USB 设备重新分区

Repartition a USB device using DiskPart

我想使用 C# 应用程序中的 DiskPart 对 USB 驱动器重新分区。这看起来相当简单:我使用 Win32_DiskDrive class 收集有关插入磁盘的数据,然后使用 DiskPart 运行 脚本来更改分区。关键点似乎是将条目 I select 从 Win32_DiskDrive 映射到 DiskPart 中的磁盘号。例如,这是 DiskPart 的输出:

DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
* Disk 0    Online          100 GB      0 B
  Disk 1    Online           14 GB      0 B

我需要 select 磁盘的编号。但是我在哪里可以从使用 Win32_DiskDrive 检索到的数据中获取该数字?我猜答案是使用 "DeviceID" 字段,其中 returns 这个“\\.\PHYSICALDRIVE0”。最后的索引似乎是我需要将 Win32_DiskDrive 中的条目与 DiskPart 中的相关条目相匹配的索引。这个对吗?关键问题是:官方文档中是否有任何地方毫无疑问地说明了这一点?然后我将格式化设备,这样我就不会在这里做错任何事。 谢谢

你需要使用 uint32 索引;

Physical drive number of the given drive. This property is filled by the STORAGE_DEVICE_NUMBER structure returned from the IOCTL_STORAGE_GET_DEVICE_NUMBER control code. A value of 0xffffffff indicates that the given drive does not map to a physical drive.


关于 DiskPart 磁盘编号 - 我没有在文档中找到明确说明此处磁盘编号的含义。但是我在调​​试器下查看磁盘的 diskpart 格式行 - 内部函数

long ListDiskLine(IVdsDisk *)

要求这样做。

它使用了IVdsDisk interface for get disk properties. the IVdsDisk::GetProperties method called for get VDS_DISK_PROP结构 然后使用 pwszName 成员:

pwszName: The null-terminated Unicode name that the operating system uses to identify the disk. If present, a client can use this property to determine the disk's PNP device number. This is the number obtained from the DeviceNumber member of STORAGE_DEVICE_NUMBER (see [MSDN-STRGEDEVNUM]). For a hard disk, this name has the format \?\PhysicalDriveN, where N signifies the device number of the disk. For a DVD/CD drive, this name has the format \?\CdRomN, where N signifies the device number of the DVD/CD drive. A client can use this property to identify the disk.

硬盘使用下一个代码获取 N:

或者如果将其翻译成 c/c++

esi = _wtol(pvdp->pwszName + RTL_NUMBER_OF("\\?\PhysicalDrive") - 1);

0x220x11*sizeof(WCHAR) 并且正好是 \?\PhysicalDrive 前缀中的 0x11 (17) 个符号。

so diskpart retriever N from \?\PhysicalDriveN 这是号码 从 DeviceNumber 成员 STORAGE_DEVICE_NUMBER 获得(因此等于 Win32_DiskDrive.Index

最后 esi(存储 N 的地方)用作:

StringCchPrintf(sz, 0x400, L"%s Disk %-3lu  %-13.13s  %7s  %7s   %s    %s\r\n", *, esi, ..);
ConsolePrintf(sz);