Jump to content

[Delphi]How To Get Windows Drives List

- - - - -

  • Please log in to reply
No replies to this topic

#1
LuthfiHakim

LuthfiHakim

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 765 posts
How To Get Drive List in Windows

There are several methods to get Windows drive list. This one is my favorite one, i.e. using Windows API GetLogicalDriveStrings since the drive letters are coming complete with trailing colon and backslash. Basically by using GetLogicalDriveStrings you get a string of available drive letters in the current system. But Windows string is a bit different with Delphi string, so we need extra steps to be able to read the information properly. Beside that, we also need to check for possible problem.

The following procedure will fill an instance of TStrings with detected drive letters.

procedure GetDriveLetters(AList: TStrings);
var
  vDrivesSize: Cardinal;
  vDrives	: array[0..128] of Char;
  vDrive	 : PChar;
begin
  AList.BeginUpdate;
  try
	// clear the list from possible leftover from prior operations
	AList.Clear;
	vDrivesSize := GetLogicalDriveStrings(SizeOf(vDrives), vDrives);
	if vDrivesSize=0 then Exit; // no drive found, no further processing needed

	vDrive := vDrives;
	while vDrive^ <> #0 do
	begin
	  AList.Add(StrPas(vDrive));
	  Inc(vDrive, SizeOf(vDrive));
	end;
  finally
	AList.EndUpdate;
  end;
end;

Here the sample of the code in action (used with a TListBox).
Attached File  GetDriveLetters_scrShot01.png   6.01K   204 downloads

Full source code for demo project is attached. Feel free to use or improve it.

Attached Files






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users