Title: Determining if a logical drive exists
Question: How to know if there is a drive assigned to a letter.
Answer:
You can use the API GetLogicalDrives to get the logical drives present in the system. This function returns a 32-bit value where the bits represent the logical units. For example:
+---------------------------------- bit 31 (most significant bit)
| +--- bit 0 (least significant bit)
| |
00000000000000000000000000101101
| ||||||||
| |||||||+--- 1 == Drive A: present
| ||||||+---- 0 == Drive B: absent
| |||||+----- 1 == Drive C: present
| ||||+------ 1 == Drive D: present
| |||+------- 0 == Drive E: absent
| ||+-------- 1 == Drive F: present
| |+--------- 0 == Drive G: absent
| +---------- 0 == Drive H: absent
| : : :
+---------------------------- 0 == Drive Z: absent
To get the bit mask corresponding to a drive letter in order to test the result of GetLogicalDrives, we can use the following expression:
1 Shl (Ord(DriveLetter) - Ord('A'))
For example, if DriveLetter was 'D', the result of this expression would be:
1 shl (Ord('D') - Ord('A')) = 1 shl (68 - 65) = 1 shl 3 = 8
In binary:
00000000000000000000000000001000
A bitwise And between the mask and the result of GetLogicalDrives will be zero if bit 3 isn't set (i.e. if drive D: isn't a valid logical drive).
All right then, let's get to the function:
uses Windows;
function IsLogicalDrive(Drive: string): boolean;
var
sDrive: string;
cDrive: char;
begin
sDrive := ExtractFileDrive(Drive);
if sDrive = '' then
Result := False
else begin
cDrive := UpCase(sDrive[1]);
if cDrive in ['A'..'Z'] then
result := (GetLogicalDrives And
(1 Shl (Ord(cDrive) - Ord('A')))) 0
else
Result := False;
end;
end;
Sample call:
if not IsLogicalDrive(Edit1.Text) then
ShowMessage(Format('"%s" is not a valid drive.',
[ExtractFileDrive(Edit1.Text)]));