我提供了一些可能有帮助的功能。第一个使用 Win32 API 函数GetLogicalDriveStrings检索计算机上已分配驱动器号的列表。第二个查询驱动器以查看它是否可以使用(其中有磁盘)。(还有一个实用函数可以将驱动器号转换为所需的整数值DiskSize
,即旧的 Pascal I/O 函数。)
该代码从 Win95 天开始就可以运行,并且刚刚在 Delphi 2007 控制台应用程序中的 Win7 64 位上进行了测试。下面包含一个控制台测试应用程序。
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils, Windows, Types;
// Returns an array filled wit the assigned
// drive letters on the current computer.
function GetDriveList: TStringDynArray;
var
Buff: array[0..128] of Char;
ptr: PChar;
Idx: Integer;
begin
if (GetLogicalDriveStrings(Length(Buff), Buff) = 0) then
RaiseLastOSError;
// There can't be more than 26 lettered drives (A..Z).
SetLength(Result, 26);
Idx := 0;
ptr := @Buff;
while StrLen(ptr) > 0 do
begin
Result[Idx] := ptr;
ptr := StrEnd(ptr);
Inc(ptr);
Inc(Idx);
end;
SetLength(Result, Idx);
end;
// Converts a drive letter into the integer drive #
// required by DiskSize().
function DOSDrive( const sDrive: String ): Integer;
begin
if (Length(sDrive) < 1) then
Result := -1
else
Result := (Ord(UpCase(sDrive[1])) - 64);
end;
// Tests the status of a drive to see if it's ready
// to access.
function DriveReady(const sDrive: String): Boolean;
var
ErrMode: Word;
begin
ErrMode := SetErrorMode(0);
SetErrorMode(ErrMode or SEM_FAILCRITICALERRORS);
try
Result := (DiskSize(DOSDrive(sDrive)) > -1);
finally
SetErrorMode(ErrMode);
end;
end;
// Demonstrates using the above functions.
var
DrivesArray: TStringDynArray;
Drive: string;
const
StatusStr = 'Drive %s is ready: %s';
begin
DrivesArray := GetDriveList;
for Drive in DrivesArray do
WriteLn(Format(StatusStr, [Drive, BoolToStr(DriveReady(Drive), True)]));
ReadLn;
end.
在我的系统上运行时的示例输出(Win7 64、两个物理硬盘驱动器(C: 和 D:)、一个未安装映像的 ISO 设备 (E:) 和一个 DVD 驱动器 (Z:)。
Drive C:\ is ready: True
Drive D:\ is ready: True
Drive E:\ is ready: False
Drive Z:\ is ready: True