Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Counting Number Of Files In Folder 1

Status
Not open for further replies.

PaidtheUmpire

Programmer
Jan 4, 2004
105
AU
I have a large amount of files in a folder, and i was wondering is there a way to count the number of them in the folder.

Any ideas?

Delphi, Delphi, Delphi. Oi! Oi! Oi!
 
Put on your form:
Button
Label

Code:
procedure TForm1.Button1Click(Sender: TObject);
begin
  CountFiles('C:\... yourFolder..');
end;
procedure tform1.CountFiles(FilePath: string);
var
  SearchRec: TSearchRec;
  fileCount: Integer;
begin
  fileCount := 0;
  if FilePath[Length(FilePath)] <> '\' then FilePath := FilePath + '\';
  if FindFirst(FilePath + '*.*', faAnyFile and not faDirectory, SearchRec) = 0 then
  begin
    Inc(fileCount);
    while FindNext(SearchRec) = 0 do
    begin
      Inc(fileCount);
    end;
  end;
  FindClose(SearchRec);
  Form1.Label1.Caption := IntToStr(fileCount) ;
end;

Have a nice day

Giovanni Caramia
 
It is probably more useful to have a CountFilesInFolder function than having it hard coded in a button event handler. Also the IncludeTrailingPathDelimiter function is a better way of ensuring that the path ends with a \.
Code:
function CountFilesInFolder ( path: string ): integer;
var
  tsr: TSearchRec;
begin
  path := IncludeTrailingPathDelimiter ( path );
  result := 0;
  if FindFirst ( path + '*.*', faAnyFile and not faDirectory, tsr ) = 0 then begin
    repeat
      inc ( result );
    until FindNext ( tsr ) <> 0;
    FindClose ( tsr );
  end;
end;

Andrew
Hampshire, UK
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top