Help & Manual authoring tool
How to get the drive letter of the CD-ROM drive unit?

Getting the drive letter of the CD-ROM drive unit

Copyright © 2000 Ernesto De Spirito

InstallAWARE - MSI without rocket science

GetLogicalDriveStrings and GetDriveType

To get the drive letter corresponding to the first CD-ROM drive in a system we'll make use of two Windows API functions: GetLogicalDriveStrings and GetDriveType. With the first one we'll retrieve the list of logical drives in a buffer. This list is a sequence of null-terminated four-character-length strings (counting the null terminator), and it ends in a null character, for example:

'a:\'#0'b:\'#0'c:\'#0'd:\'#0'f:\'#0#0

With GetDriveType we can determine if a given drive is a CD-ROM drive by checking if the return value is the constant DRIVE_CDROM.

The following function returns the first logical drive that corresponds to a CDROM drive. The function returns an empty string ('') if no CDROM drive was found.

uses Windows;

function GetFirstCdRomDrive: string;
var
  r: LongWord;
  Drives: array[0..128] of char;
  pDrive: pchar;
begin
  Result := '';
  r := GetLogicalDriveStrings(sizeof(Drives), Drives);
  if r = 0 then exit;
  if r > sizeof(Drives) then
    raise Exception.Create(SysErrorMessage(ERROR_OUTOFMEMORY));
  pDrive := Drives;  // Point to the first drive
  while pDrive^ <> #0 do begin
    if GetDriveType(pDrive) = DRIVE_CDROM then begin
      Result := pDrive;
      exit;
    end;
    inc(pDrive, 4);  // Point to the next drive
  end;
end;

Sample call

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetFirstCdRomDrive);
end;
JfControls Library - for Delphi and C++ Builder
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.