gpt4 book ai didi

delphi - 如何获取USB设备的盘符?

转载 作者:行者123 更新时间:2023-12-03 14:51:00 32 4
gpt4 key购买 nike

我正在使用 WMI 获取所有插入的 USB 磁盘制造商名称。该代码工作得很好,但我有一个问题,如何确定某个磁盘具有的驱动器号...我只能获取设备名称,例如

(\\.\PhysicalDrive1) ...我如何将其翻译为普通驱动器号?

最佳答案

如果您获得类似 \\.\PHYSICALDRIVE1 的值,则表示您正在使用 Win32_DiskDrive wmi 类和 DeviceID Property ,因此为了获取驱动器盘符您必须使用 ASSOCIATORS 类,它将在包含您正在查找的信息 (Win32_LogicalDisk) 的 wmi 类和您正在使用的类 (Win32_DiskDrive) 之间创建链接。

所以你必须做这样的事情

Win32_DiskDrive-> Win32_DiskDriveToDiskPartition -> Win32_DiskPartition -> Win32_LogicalDiskToPartition -> Win32_LogicalDisk

检查此示例函数

{$APPTYPE CONSOLE}

uses
SysUtils,
ActiveX,
ComObj,
Variants;


function DeviceIDToDrive(const ADeviceID : string) : string;
var
FSWbemLocator : OLEVariant;
objWMIService : OLEVariant;
colLogicalDisks: OLEVariant;
colPartitions : OLEVariant;
objPartition : OLEVariant;
objLogicalDisk : OLEVariant;
oEnumPartition : IEnumvariant;
oEnumLogical : IEnumvariant;
iValue : LongWord;
DeviceID : string;
begin;
Result:='';
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
objWMIService := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
DeviceID := StringReplace(ADeviceID,'\','\\',[rfReplaceAll]); //Escape the `\` chars in the DeviceID value because the '\' is a reserved character in WMI.
colPartitions := objWMIService.ExecQuery(Format('ASSOCIATORS OF {Win32_DiskDrive.DeviceID="%s"} WHERE AssocClass = Win32_DiskDriveToDiskPartition',[DeviceID]));//link the Win32_DiskDrive class with the Win32_DiskDriveToDiskPartition class
oEnumPartition := IUnknown(colPartitions._NewEnum) as IEnumVariant;
while oEnumPartition.Next(1, objPartition, iValue) = 0 do
begin
if not VarIsNull(objPartition.DeviceID) then
begin
colLogicalDisks := objWMIService.ExecQuery('ASSOCIATORS OF {Win32_DiskPartition.DeviceID="'+VarToStr(objPartition.DeviceID)+'"} WHERE AssocClass = Win32_LogicalDiskToPartition'); //link the Win32_DiskPartition class with theWin32_LogicalDiskToPartition class.
oEnumLogical := IUnknown(colLogicalDisks._NewEnum) as IEnumVariant;
if oEnumLogical.Next(1, objLogicalDisk, iValue) = 0 then
begin
Result:=objLogicalDisk.DeviceID;
objLogicalDisk:=Unassigned;
end;
end;
objPartition:=Unassigned;
end;
end;

begin
try
CoInitialize(nil);
try
Writeln(DeviceIDToDrive('\\.\PHYSICALDRIVE2'));
finally
CoUninitialize;
end;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Readln;
end.

关于delphi - 如何获取USB设备的盘符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6653205/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com