[函数]获取物理路径对应的磁盘序号

这个函数是我找了好久,然后在百度和MSDN翻来翻去后,终于写出来的一个函数。百度的函数要求的权限太大,在Windows 7以后用不了。

type
  STORAGE_DEVICE_NUMBER = record
    DeviceType: Word;
    DeviceNumber: Cardinal;
    PartitionNumber: ULONG;
  end;
/// <summary>获取物理路径对应的磁盘序号</summary>
/// <param name="APath">目录名,只支持绝对路径名,如"C:\temp",不能是相对路径</param>
/// <returns>返回当前目录对应的磁盘序号,-1代表未找到。</returns>

function TForm6.GetPhysicalDriveNo(APath: QStringW): Integer;
var
  hDev: THandle;
  AResult: Boolean;
  AReaded: Cardinal;
  ANumber: STORAGE_DEVICE_NUMBER;
begin
APath := '\\.\' + Copy(APath, 1, 2);
Result := -1;
hDev := CreateFileW(PQCharW(APath), FILE_READ_ATTRIBUTES or SYNCHRONIZE or FILE_TRAVERSE, FILE_SHARE_READ or
  FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
if hDev <> INVALID_HANDLE_VALUE then
  begin
  AResult := DeviceIoControl(hDev, IOCTL_STORAGE_GET_DEVICE_NUMBER, nil, 0,
    @ANumber, SizeOf(ANumber), AReaded, nil);
  if AResult then
    Result := ANumber.DeviceNumber;
  CloseHandle(hDev);
  end;
end;

运行效果:

QQ截图20141208154839

分享到: