I want DefaultDirName to be selected on the hard disk drive with maximum free space

Viewed 94

I am creating an installation using Inno Setup. I want DefaultDirName to be selected on the hard disk drive with maximum free space.

1 Answers

Implement a scripted constant to select the disk. Use GetDriveType WinAPI function to filter to fixed drives (DRIVE_FIXED) and GetSpaceOnDisk64 function to query the free disk space.

[Setup]
DefaultDirName={code:GetDiskWithMostFreeSpace}My Program
[Code]

const
  DRIVE_NO_ROOT_DIR = 1;
  DRIVE_FIXED = 3;
  
function GetDriveType(lpRootPathName: string): UInt;
  external 'GetDriveTypeW@kernel32.dll stdcall';

function GetDiskWithMostFreeSpace(Param: string): string;
var
  I: Integer;
  D: string;
  MostFree: Int64;
  Free, Total: Int64;
  T: UInt;
begin
  Result := '';
  MostFree := -1;
  for I := Ord('A') to Ord('Z') do
  begin
    D := Chr(I) + ':\';
    T := GetDriveType(D);
    if T = DRIVE_NO_ROOT_DIR then
    begin
      Log(Format('Disk %s does not exist', [D]));
    end
      else
    begin
      Log(Format('Disk %s is of type %d', [D, T]));
      if T = DRIVE_FIXED then
      begin
        if not GetSpaceOnDisk64(D, Free, Total) then
        begin
          Log(Format('Cannot obtain free disk space on %s', [D]));
        end
          else
        begin
          Log(Format('Free disk space on %s is %d', [D, Free]));
          if Free > MostFree then
          begin
            MostFree := Free;
            Result := D;
          end;
        end;
      end;
    end;
  end;

  if Result = '' then
  begin
    RaiseException('Did not find any disk');
  end;

  Log(Format('Selected disk %s', [Result]));
end;

The code might be improved with use of GetVolumeInformation, as seen in How to check partition type in Inno Setup?

Related