How to Get File Size in Bytes using Delphi / Object Pascal ?


If you want to get the file size in bytes for a file, you can use the following function in Delphi/Object Pascal.

// maxium supports 2G
function getFileSizeInBytes(const fn: string): integer;
var
  f: File of byte;
begin
  Result := -1;
  if (FileExists(fn)) then
  begin
    try
      {$I-}
      AssignFile(f, fn);
      Reset(f);
      {$I+}
      if (IOResult = 0) then
      begin
        Result := FileSize(f);
      end
      else
      begin
        Result := 0;
      end;
    finally
      {$I-}CloseFile(f);{$I+}
    end;
  end;
end;

In order to use this function, you have to provide a parameter which is the path to the file name. And the function will return a 4 byte signed integer. negative 1 means file not found or cannot be accessed (opened). Otherwise, a maximum 2GB file size in bytes is supported.

We use {$I-} to disable the IO Check and the Win32 API FileSize to return the size in bytes.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
199 words
Last Post: Allow ASP Style Short_Open_Tag in PHP.ini
Next Post: How to Convert JPEG to BMP and BMP to JPEG in Object Pascal / Delphi ?

The Permanent URL is: How to Get File Size in Bytes using Delphi / Object Pascal ?

2 Comments

  1. Mark Johnson
  2. Oz

Leave a Reply