delphifiledelphi-2010

Getting size of a file in Delphi 2010 or later?


Delphi 2010 has a nice set of new file access functions in IOUtils.pas (I especially like the UTC versions of the date-related functions). What I miss so far is something like

TFile.GetSize (const Path : String)

What is the Delphi 2010-way to get the size of a file? Do I have to go back and use FindFirst to access TSearchRec.FindData?

Thanks.


Solution

  • I'm not sure if there's a "Delphi 2010" way, but there is a Windows way that doesn't involve FindFirst and all that jazz.

    I threw together this Delphi conversion of that routine (and in the process modified it to handle > 4GB size files, should you need that).

      uses
        WinApi.Windows;
    
      function FileSize(const aFilename: String): Int64;
      var
        info: TWin32FileAttributeData;
      begin
        result := -1;
    
        if NOT GetFileAttributesEx(PChar(aFileName), GetFileExInfoStandard, @info) then
          EXIT;
    
        result := Int64(info.nFileSizeLow) or Int64(info.nFileSizeHigh shl 32);
      end;
    

    You could actually just use GetFileSize() but this requires a file HANDLE, not just a file name, and similar to the GetCompressedFileSize() suggestion, this requires two variables to call. Both GetFileSize() and GetCompressedFileSize() overload their return value, so testing for success and ensuring a valid result is just that little bit more awkward.

    GetFileSizeEx() avoids the nitty gritty of handling > 4GB file sizes and detecting valid results, but also requires a file HANDLE, rather than a name, and (as of Delphi 2009 at least, I haven't checked 2010) isn't declared for you in the VCL anywhere, you would have to provide your own import declaration.