获取特定驱动器的GUID

时间:2016-06-30 11:11:48

标签: windows delphi winapi

我想找出特定驱动器号的Drive-GUID。 我有以下代码:

Function GetVolumeNameForVolumeMountPoint(lpszVolumeMountPoint: LPCTSTR; lpszVolumeName: LPTSTR; cchBufferLength: DWORD): BOOL; stdcall;
  external 'kernel32.dll' name 'GetVolumeNameForVolumeMountPointW';

procedure TForm1.Button1Click(Sender: TObject);
var
  Buffer: array[0..50] of AnsiChar;
begin
  if GetVolumeNameForVolumeMountPoint('C:\', Buffer, SizeOf(Buffer)) then
  begin
    showmessage(buffer); // Expected: "\\?\Volume{deadbeef-895e-4a1d-9d64-9b82fa068d76}\"
  end
  else RaiseLastOSError; // Actual: ERROR_INVALID_NAME (123).
end;

我收到错误ERROR_INVALID_NAME (123),但我不知道为什么。我做错了什么?

1 个答案:

答案 0 :(得分:10)

您正在调用函数的Unicode版本,但是传递ANSI文本。因此,您传递的第一个参数被错误编码,因此错误消息。

该程序演示了应该如何完成:

{$APPTYPE CONSOLE}

uses
  SysUtils, Windows;

function GetVolumeNameForVolumeMountPointA(lpszVolumeMountPoint: PAnsiChar;
  lpszVolumeName: PAnsiChar; cchBufferLength: DWORD): BOOL; stdcall;
  external 'kernel32.dll';

procedure Main;
var
  Buffer: array [0 .. 49] of AnsiChar;
begin
  Win32Check(GetVolumeNameForVolumeMountPointA('C:\', Buffer, Length(Buffer)));
  Writeln(Buffer);
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

由于很明显您使用的是Unicode前版本的Delphi(否则您的程序无法编译),我已经为您提供了上面的ANSI代码。如果您曾升级到Unicode版本的Delphi,那么您可以这样写:

{$APPTYPE CONSOLE}

uses
  SysUtils, Windows;

function GetVolumeNameForVolumeMountPointW(lpszVolumeMountPoint: PWideChar;
  lpszVolumeName: PWideChar; cchBufferLength: DWORD): BOOL; stdcall;
  external 'kernel32.dll';

procedure Main;
var
  Buffer: array [0 .. 49] of WideChar;
begin
  Win32Check(GetVolumeNameForVolumeMountPointW('C:\', Buffer, Length(Buffer)));
  Writeln(Buffer);
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

或者,如果您想要在所有版本的Delphi中运行的代码,您可以这样做:

{$APPTYPE CONSOLE}

uses
  SysUtils, Windows;

const
  Win32ImportSuffix = {$IFDEF Unicode}'W'{$ELSE}'A'{$ENDIF};

function GetVolumeNameForVolumeMountPointA(lpszVolumeMountPoint: PAnsiChar;
  lpszVolumeName: PAnsiChar; cchBufferLength: DWORD): BOOL; stdcall;
  external 'kernel32.dll';
function GetVolumeNameForVolumeMountPointW(lpszVolumeMountPoint: PWideChar;
  lpszVolumeName: PWideChar; cchBufferLength: DWORD): BOOL; stdcall;
  external 'kernel32.dll';
function GetVolumeNameForVolumeMountPoint(lpszVolumeMountPoint: PChar;
  lpszVolumeName: PChar; cchBufferLength: DWORD): BOOL; stdcall;
  external 'kernel32.dll' name 'GetVolumeNameForVolumeMountPoint' + Win32ImportSuffix;

procedure Main;
var
  Buffer: array [0 .. 49] of Char;
begin
  Win32Check(GetVolumeNameForVolumeMountPoint('C:\', Buffer, Length(Buffer)));
  Writeln(Buffer);
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.