Title: How do I determine the available disk space on a drive?
This method returns the free space and capacity of the drive specified by DriveLetter.
CODE
function GetAvailableSpace(DriveLetter: Char): String;
var
DiskCapacity, FreeSpace: Extended;
begin
DriveLetter := UpCase(DriveLetter);
DiskCapacity := DiskSize(Ord(DriveLetter) - 64) / 1048576;
FreeSpace := DiskFree(Ord(DriveLetter) - 64) / 1048576;
if DiskCapacity 1000 then
begin
DiskCapacity := DiskCapacity / 1024;
FreeSpace := FreeSpace / 1024;
Result := FormatFloat('#,##0.00', FreeSpace) + 'GB of ' + FormatFloat('#,##0.00', DiskCapacity) + 'GB';
end
else
Result := FormatFloat('#,##0', FreeSpace) + 'MB of ' + FormatFloat('#,##0', DiskCapacity) + 'MB';
end;
An example of its use is in the code below. The following code runs through drives B to Z, checks if the drive is a hard drive (i.e. a fixed disk) before calling the GetAvailableSpace function, and adds the returned string to ValueListEditor1.
CODE
procedure TForm1.Button1Click(Sender: TObject);
var
driveLetter: Char;
begin
for driveLetter := 'B' to 'Z' do
begin
if GetDriveType(PChar(driveLetter + ':\')) = DRIVE_FIXED then
ValueListEditor1.InsertRow('Available Space (' + driveLetter + ':)',
GetAvailableSpace(driveLetter), True);
end;
end;