[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 601
  • Last Modified:

Get size of file

before anyone gives me examples read on first.......


Does anyone have examples on how to use the Windows API to get the size of a file in bytes - must be able to handle HUGE files (ie: any size of file on a Windows system 4Gb upwards).

I want to use Windows API as i am assuming it is faster than going through the delphi way.
0
mi6agent
Asked:
mi6agent
  • 2
  • 2
2 Solutions
 
geobulCommented:
Hi,

Try this:

function GetFileSize(const strFile: string): Int64;
var
  SearchRec:TSearchRec;
begin
  result := 0;
  if (FindFirst(strFile, faAnyFile, SearchRec)=0) then begin
    // File found.
    result := (Int64(SearchRec.FindData.nFileSizeHigh) shl 32) + SearchRec.FindData.nFileSizeLow;
  end;
  FindClose(SearchRec);
end;

usage:
ShowMessage(IntToStr(GetFileSize(Edit1.Text)));

Regards, Geo
0
 
DragonSlayerCommented:
Let's see if this works:

uses
  Windows;

function GetHugeSize(const S: string): Int64;
var
  fHandle: THandle;
  size: TLargeInteger;
begin
  Result := 0;
  fHandle := CreateFile(PChar(S), GENERIC_READ, 0, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  try
    // here's the trick, making used of a record
    size.LowPart := GetFileSize(fHandle, @size.HighPart);
    Result := size.QuadPart;
  finally
    CloseHandle(fHandle);
  end;
end;



DragonSlayer.
0
 
DragonSlayerCommented:
LoL, sorry, didn't see Geo's comment... didn't press Refresh :-p
0
 
geobulCommented:
Another version (API only):

function GetFileSize(const strFile: string): Int64;
var
  h: THandle;
  FindData:TWin32FindData;
begin
  result := 0;
  h := windows.FindFirstFile(PChar(strFile), FindData);
  if (h > 0) then begin
    // File found.
    result := (Int64(FindData.nFileSizeHigh) shl 32) + FindData.nFileSizeLow;
  end;
  windows.FindClose(h);
end;

Regards, Geo
0
 
mi6agentAuthor Commented:
Thanks to both of you - i have raised the points and split them to give origianl 125 points each.

DragonSlayer - i used your code BUT changed OPEN_ALWAYS to OPEN_EXISTING - OPEN_ALWAYS will create the file if it is not found.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now