windows 如何获取 U 盘的制造商序列号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4292395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get manufacturer serial number of an USB flash drive?
提问by opc0de
How can I retrieve the manufacturer serial number of an USB flash drive in Delphi ?
如何在 Delphi 中检索 USB 闪存驱动器的制造商序列号?
I have tried this:
我试过这个:
function GetDiskVolSerialID(ADriveName: Char): Cardinal;
var
DiskDrive: string;
FileSystemFlags: DWORD;
VolumeSerialNumber: DWORD;
MaximumComponentLength: DWORD;
begin
DiskDrive := ADriveName + ':\';
GetVolumeInformation(PChar(DiskDrive),
nil,
0,
@VolumeSerialNumber,
MaximumComponentLength,
FileSystemFlags,
nil,
0);
Result := VolumeSerialNumber;
end;
But it doesn't return correct result!
但它没有返回正确的结果!
回答by RRUZ
opc0de, according to your commentsi will give you a sample using the WMI.
opc0de,根据您的意见,我会给您一个使用 WMI 的示例。
First, the code which you posted (using the GetVolumeInformation
function) return the serial number assigned by windows when you format a disk.
首先,您发布的代码(使用该GetVolumeInformation
函数)在格式化磁盘时返回 Windows 分配的序列号。
The good news are which exist two wmi classes wich exposes a property called SerialNumber
which store the Number allocated by the manufacturer to identify the physical media.
these classes are Win32_DiskDrive
and Win32_PhysicalMedia
.
好消息是存在两个 wmi 类,它们公开了一个名为SerialNumber
which storethe Number allocated by the manufacturer to identify the physical media.
这些类是 Win32_DiskDrive
and的属性Win32_PhysicalMedia
。
Now the bad news, unfortunately this classes is not associated directly with the letter (C,D,E,F...) of the logical disk, because that you must call to another wmi classes to find the link between the logical driver letter and the Physical drive.
现在坏消息是,不幸的是,这些类没有直接与逻辑磁盘的字母 (C,D,E,F...) 关联,因为您必须调用另一个 wmi 类才能找到逻辑驱动程序字母之间的链接和物理驱动器。
so you must find this link previous to obtain the serial number. the sequence to find this association is like this.
所以你必须在之前找到这个链接才能获得序列号。找到这个关联的顺序是这样的。
Win32_DiskPartition
-> Win32_LogicalDiskToPartition
-> Win32_DiskDrive
Win32_DiskPartition
-> Win32_LogicalDiskToPartition
->Win32_DiskDrive
this is the code to obtain the serial number of a usb using the Win32_DiskDrive
class.
这是使用Win32_DiskDrive
该类获取 USB 序列号的代码。
program GetWMI_Info;
{$APPTYPE CONSOLE}
uses
SysUtils,
StrUtils,
ActiveX,
ComObj,
Variants;
function VarArrayToStr(const vArray: variant): string;
function _VarToStr(const V: variant): string;
var
Vt: integer;
begin
Vt := VarType(V);
case Vt of
varSmallint,
varInteger : Result := IntToStr(integer(V));
varSingle,
varDouble,
varCurrency : Result := FloatToStr(Double(V));
varDate : Result := VarToStr(V);
varOleStr : Result := WideString(V);
varBoolean : Result := VarToStr(V);
varVariant : Result := VarToStr(Variant(V));
varByte : Result := char(byte(V));
varString : Result := String(V);
varArray : Result := VarArrayToStr(Variant(V));
end;
end;
var
i : integer;
begin
Result := '[';
if (VarType(vArray) and VarArray)=0 then
Result := _VarToStr(vArray)
else
for i := VarArrayLowBound(vArray, 1) to VarArrayHighBound(vArray, 1) do
if i=VarArrayLowBound(vArray, 1) then
Result := Result+_VarToStr(vArray[i])
else
Result := Result+'|'+_VarToStr(vArray[i]);
Result:=Result+']';
end;
function VarStrNull(const V:OleVariant):string; //avoid problems with null strings
begin
Result:='';
if not VarIsNull(V) then
begin
if VarIsArray(V) then
Result:=VarArrayToStr(V)
else
Result:=VarToStr(V);
end;
end;
function GetWMIObject(const objectName: String): IDispatch; //create the Wmi instance
var
chEaten: Integer;
BindCtx: IBindCtx;
Moniker: IMoniker;
begin
OleCheck(CreateBindCtx(0, bindCtx));
OleCheck(MkParseDisplayName(BindCtx, StringToOleStr(objectName), chEaten, Moniker));
OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result));
end;
function GetUsbDriveSerial(const Drive:AnsiChar):string;
var
objWMIService : OLEVariant;
colDiskDrives : OLEVariant;
colLogicalDisks: OLEVariant;
colPartitions : OLEVariant;
objDiskDrive : OLEVariant;
objPartition : OLEVariant;
objLogicalDisk : OLEVariant;
oEnumDiskDrive : IEnumvariant;
oEnumPartition : IEnumvariant;
oEnumLogical : IEnumvariant;
iValue : LongWord;
DeviceID : string;
begin;
Result:='';
objWMIService := GetWMIObject('winmgmts:\localhost\root\CIMV2'); //Connect to the WMI
//colDiskDrives := objWMIService.ExecQuery('SELECT DeviceID,SerialNumber FROM Win32_DiskDrive WHERE InterfaceType="USB"','WQL',0);
colDiskDrives := objWMIService.ExecQuery('SELECT * FROM Win32_DiskDrive WHERE InterfaceType="USB"','WQL',0);
oEnumDiskDrive:= IUnknown(colDiskDrives._NewEnum) as IEnumVariant;
while oEnumDiskDrive.Next(1, objDiskDrive, iValue) = 0 do
begin
DeviceID := StringReplace(VarStrNull(objDiskDrive.DeviceID),'\','\',[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
colLogicalDisks := objWMIService.ExecQuery('ASSOCIATORS OF {Win32_DiskPartition.DeviceID="'+VarStrNull(objPartition.DeviceID)+'"} WHERE AssocClass = Win32_LogicalDiskToPartition'); //link the Win32_DiskPartition class with theWin32_LogicalDiskToPartition class.
oEnumLogical := IUnknown(colLogicalDisks._NewEnum) as IEnumVariant;
while oEnumLogical.Next(1, objLogicalDisk, iValue) = 0 do
if VarStrNull(objLogicalDisk.DeviceID)=(Drive+':') then //compare the device id
begin
Result:=VarStrNull(objDiskDrive.SerialNumber);
Exit;
end;
end;
end;
end;
begin
try
CoInitialize(nil);
try
Writeln(GetUsbDriveSerial('F'));
Readln;
finally
CoUninitialize;
end;
except
on E:Exception do
begin
Writeln(E.Classname, ':', E.Message);
Readln;
end;
end;
end.
By the way some time ago i wrote an application called WMI Delphi Code Creatorwhich can help you to generate delphi code to access the system info using the WMI.
顺便说一句,前段时间我写了一个名为WMI Delphi Code Creator的应用程序,它可以帮助您生成 Delphi 代码以使用 WMI 访问系统信息。
UPDATE
更新
Some drivers of the USB disks does not expose the manufacturer serial number on the Win32_DiskDrive.SerialNumber property, so on this cases you can extract the serial number from the PnPDeviceID
property.
部分U盘驱动没有在Win32_DiskDrive.SerialNumber属性上暴露厂商序列号,所以这种情况下可以从PnPDeviceID
属性中提取序列号。
Check this sample code.
检查此示例代码。
{$APPTYPE CONSOLE}
uses
SysUtils,
StrUtils,
ActiveX,
ComObj,
Variants;
function VarStrNull(const V:OleVariant):string; //avoid issues with null variants
begin
Result:='';
if not VarIsNull(V) then
Result:=VarToStr(V);
end;
function GetUsbDriveSerial(const Drive:AnsiChar):string;
var
FSWbemLocator : OleVariant;
objWMIService : OLEVariant;
colDiskDrives : OLEVariant;
colLogicalDisks: OLEVariant;
colPartitions : OLEVariant;
objDiskDrive : OLEVariant;
objPartition : OLEVariant;
objLogicalDisk : OLEVariant;
oEnumDiskDrive : IEnumvariant;
oEnumPartition : IEnumvariant;
oEnumLogical : IEnumvariant;
iValue : LongWord;
DeviceID : string;
begin;
Result:='';
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
objWMIService := FSWbemLocator.ConnectServer('.', 'root\CIMV2', '', '');
colDiskDrives := objWMIService.ExecQuery('SELECT * FROM Win32_DiskDrive WHERE InterfaceType="USB"','WQL',0);
oEnumDiskDrive:= IUnknown(colDiskDrives._NewEnum) as IEnumVariant;
while oEnumDiskDrive.Next(1, objDiskDrive, iValue) = 0 do
begin
DeviceID := StringReplace(VarStrNull(objDiskDrive.DeviceID),'\','\',[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
colLogicalDisks := objWMIService.ExecQuery('ASSOCIATORS OF {Win32_DiskPartition.DeviceID="'+VarStrNull(objPartition.DeviceID)+'"} WHERE AssocClass = Win32_LogicalDiskToPartition'); //link the Win32_DiskPartition class with theWin32_LogicalDiskToPartition class.
oEnumLogical := IUnknown(colLogicalDisks._NewEnum) as IEnumVariant;
while oEnumLogical.Next(1, objLogicalDisk, iValue) = 0 do
begin
if SameText(VarStrNull(objLogicalDisk.DeviceID),Drive+':') then //compare the device id
begin
Result:=VarStrNull(objDiskDrive.PnPDeviceID);
if AnsiStartsText('USBSTOR', Result) then
begin
iValue:=LastDelimiter('\', Result);
Result:=Copy(Result, iValue+1, Length(Result));
end;
objLogicalDisk:=Unassigned;
Exit;
end;
objLogicalDisk:=Unassigned;
end;
objPartition:=Unassigned;
end;
objDiskDrive:=Unassigned;
end;
end;
begin
try
CoInitialize(nil);
try
Writeln(GetUsbDriveSerial('F'));
Readln;
finally
CoUninitialize;
end;
except
on E:Exception do
begin
Writeln(E.Classname, ':', E.Message);
Readln;
end;
end;
end.
回答by Germán Estévez -Neftalí-
You can try the component TDiskInfo from GLibto Get the SerialNumber.
It not use WMI, but in some system (disk types) not retrieve the number.
Try it. It's free.
您可以尝试使用GLib 中的组件TDiskInfo来获取 SerialNumber。
它不使用 WMI,但在某些系统(磁盘类型)中不检索数字。
尝试一下。免费。
Regards.
问候。