2008. április 16., szerda

How to determine the size of a file


Problem/Question/Abstract:

How to determine the size of a file

Answer:

Solve 1:

You can use the type TSearchRec as follows:

function LoadSize(Path: string): integer;
var
  Rec: TSearchRec;
begin
  Result := 0;
  if FindFirst(Path, faAnyFile, Rec) = 0 then
  begin
    Result := Rec.Size;
    FindClose(Rec);
  end;
end;


Solve 2:

{ ... }
var
  fileInfo: _WIN32_FILE_ATTRIBUTE_DATA;
  totalSize: Int64;
begin
  GetFileAttributesEx(PChar(EdtPath.Text), GetFileExInfoStandard, @fileInfo);
  totalSize := fileInfo.nFileSizeHigh shl 32 or fileInfo.nFileSizeLow;
end;


Solve 3:

{ ... }
var
  SR: TSearchRec;
  FileName: string;
  r: integer;
begin
  FileName := 'c:\winnt\system32\shell32.dll';
  r := FindFirst(FileName, faAnyFile, SR);
  if r = 0 then
  begin
    Label1.Caption := Format('Size of %s is %d bytes (%0.1f Mb)',
      [FileName, SR.Size, Sr.Size / 1000000]);
    FindClose(SR);
  end
  else
    Label1.Caption := 'File does not exist';
end;


Solve 4:

procedure TForm1.Button1Click(Sender: TObject);
var
  hFile: THandle;
  Size: Integer;
begin
  if OpenDialog1.Execute then
  begin
    hFile := FileOpen(OpenDialog1.FileName, fmOpenRead or fmShareDenyNone);
    Size := GetFileSize(hFile, nil);
    {CloseHandle: use to close handle created with CreateFile which is
                what FileOpen calls internally}
    CloseHandle(hFile);
    ShowMessage(Format('Size in bytes: %d', [Size]));
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése