Title: How to get a file's size like Microsoft
Question: The windows API provides a number of different ways to return the size of a file, however all of the return values are in bytes. Using a library named SHLWAPI.DLL, you can return file sizes in a format like "1.32 MB". (just like Windows Explorer)
Answer:
//Use this API from SHLWAPI.DLL to format file sizes into proper strings like
//Windows Explorer. The file SHLWAPI.DLL is shipped with IE4 and greater. The
//file can be found with Windows 95 + IE4, Windows 98, Windows ME, Windows NT4
//and Windows 2000.
//To load the API implicitly you should add this line to your external dll's:
//function StrFormatByteSizeA(dw: integer; pszBuf: PChar; cchBuf: integer): PChar; stdcall; external 'shlwapi.dll';
//You don't have to load the call implicitly if you use the function below:
function GetFileSizeEx(iFile: integer): string;
type
TFileSizeEx = function(dw: integer; pszBuf: PChar; cchBuf: integer): PChar; stdcall;
var
shlwapi_handle: THandle;
iFile_FileSize: integer;
Calculate_Size: TFileSizeEx;
lpSize: array [0..50] of char;
begin
if iFile 0 then
begin
iFile_FileSize := GetFileSize(iFile, nil);
shlwapi_handle := LoadLibrary('shlwapi.dll');
if shlwapi_handle = 0 then
Result := InttoStr(iFile_FileSize) + ' bytes'
else
begin
@Calculate_Size := GetProcAddress(shlwapi_handle, 'StrFormatByteSizeA');
if @Calculate_Size = nil then
Result := InttoStr(iFile_FileSize) + ' bytes'
else
begin
Calculate_Size(iFile_FileSize, lpSize, 50);
Result := lpSize;
end;
end;
end
else
Result := 'File Not Found';
FreeLibrary(shlwapi_handle);
end;
//To use the GetFileSizeEx function, add code like this to a Button's click:
procedure TForm1.Button1Click(Sender: TObject);
var
iOpenFile: integer;
begin
iOpenFile := FileOpen('c:\windows\system.dat', fmShareCompat or fmShareDenyNone);
ShowMessage(GetFileSizeEx(iOpenFile));
FileClose(iOpenFile);
end;