Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free disk space on a network drive in Delphi

I am making a program for A2 Computing which exports a lot of data. My HDD allocation on the local network is about 50 MB, so it's a good candidate to test the "no disk space" error.

Currently when the program runs out of space it crashes mid-export with I/O Error 112. I would like to warn ahead of time if the file might exceed available space. I know how big the file will be (24.8 bytes per record, on average), so all I need to do is find out how much space is free.

As I am working on a network drive, with a file path like \\qmcsan1\Cxxxxx$\filename.csv, how do I use functions like DiskFree to calculate available space? Any such function also needs to handle local drives like C:/.

Any ideas much appreciated.

like image 977
Thomas O Avatar asked Dec 15 '11 09:12

Thomas O


1 Answers

One easy approach is to call the GetDiskFreeSpaceEx API function.

Unfortunately this function is mis-declared in the Delphi Windows unit, at least it is in XE2. But there is a version declared in SysUtils which is correct. Make sure you use that version!

program FreeDiskSpace;
{$APPTYPE CONSOLE}
uses
  SysUtils;

const
  Folder = 'C:\';

var
  FreeAvailable, TotalSpace: Int64;

begin
  if SysUtils.GetDiskFreeSpaceEx(PChar(Folder), FreeAvailable, TotalSpace, nil) then begin
    Writeln(TotalSpace div (1024*1024*1024), 'GB total');
    Writeln(FreeAvailable div (1024*1024*1024), 'GB free');
  end;
end.
like image 183
David Heffernan Avatar answered Sep 23 '22 11:09

David Heffernan