How to Get Free Space Size on Disks Larger than 2.1GB

To get the free space size on a drive larger than 2.1 GB you should use the GetDiskFreeSpaceEx() function from Kernel32.dll. Although Delphi 3+ has the function implemention in the Windows unit I have decided to include it’s Delphi port.

!!Note: This function has been introduced in Windows 95 OSR 2 (95b), so you won’t find it in the first edition of Windows 95.

{ Conditional check for Delphi 3 or newer }
{$ifdef Delphi3Up}
  {$undef Delphi3Up}
{$endif}
{$ifdef 130} {Delphi 5}
  {$define Delphi3Up}
{$else}
  {$ifdef 120} {Delphi 4}
    {$define Delphi3Up}
  {$else}
    {$ifdef 100} {Delphi 3}
      {$define Delphi3Up}
    {$endif}
  {$endif}
{$endif}

Here is the function code:

function GetDiskFreeSpace(sDrv: string; var cFree, cSize: Comp): Boolean;
type
{$ifdef Delphi3Up} { Use Int64 for Delphi 3+ }
  LargeInt = Int64;
  pLargeInt = ^Int64;
{$else}
  LargeInt = Comp;
  pLargeInt = ^Comp;
{$endif}
var
  { The Windows API function reference }
  GetDiskFreeSpaceEx: function(RootName: PChar; var FreeForCaller, TotNoOfBytes: LargeInt;
    TotNoOfFreeBytes: PLargeInt): Bool; stdcall;
  cFree2, cSize2: Comp;
  hndLib: THandle;
begin
  Result := False;
  cFree2 := -1;
  cSize2 := -1;
  hndLib := GetModuleHandle('Kernel32'); { Get the handle for kernel32.dll }
  if hndLib <> 0 then begin
    @GetDiskFreeSpaceEx := GetProcAddress(Lib, 'GetDiskFreeSpaceExA');
    if (@GetDiskFreeSpaceEx <> nil) and GetDiskFreeSpaceEx(PChar(sDrv), cFree2, cSize2, nil) then begin
      cFree := cFree2;
      cSize := cSize2;
      Result := True;
    end;
    FreeLibrary(hndLib);
  end;
end;

Tags: , , , , , , , , , , , , , , ,

No Comments Yet

You can be the first to comment!

Leave a comment

OpenID Login

Standard Login