Arquivos - mostrando tamanho igual ao explorer

Top  Previous  Next

// 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)

// 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';

 

function GetFileSizeEx(const Arquivo: string): string;

type

    TFileSizeEx = function(dw: integer; pszBuf: PChar; cchBuf: integer): PChar; stdcall;

var

    shlwapi_handle: THandle;

    iFile         : Integer;

    iFile_FileSize: Integer;

    Calculate_Size: TFileSizeEx;

    lpSize        : array[0..50of char;

begin

  iFile:= FileOpen(Arquivo, fmShareCompat or fmShareDenyNone);

  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);

  FileClose(iFile);

end;

 

procedure TForm1.Button1Click(Sender: TObject);

begin

  Label1.Caption := GetFileSizeEx('c:\winnt\explorer.exe');

  Label2.Caption := GetFileSizeEx('C:\WINNT\Corel\Uninst32.exe');

  Label3.Caption := GetFileSizeEx('C:\flavio.jr');

end;