Search code examples
stringdelphidelphi-xe3memo

Add String of TSearchrec to Memo


I want to add the files in the selected folder to the memobox or in a stringlist and show the results. In both ways, i can add them but i can't show the files from the folder in the memo or from the stringlist in a ShowMessage-dialog.

function CountFilesInFolder(AFolder: String; AMask: String): Integer;
var 
  tmp1: TSearchRec;
  ergebnis: Integer;
  memo1: string;
  list : TStringList;
begin
  result := 0;
  if (AFolder <> '') then
  begin
    if AFolder[length(AFolder)] <> '\' then AFolder := AFolder + '\';
    ergebnis := FindFirst(AFolder + AMask, faArchive + faReadOnly + faHidden + faSysFile, tmp1);
      while ergebnis = 0 do
      begin
        Inc(result);
        ergebnis := FindNext(tmp1);
        while ((tmp1.Name = '|*_tif.tif')) and (ergebnis <> 0) do
        ergebnis := FindNext(tmp1);
      end;
       list.Add(tmp1.Name);
       FindClose(tmp1);
  end;
end;

thank you for your time and sorry for my bad english.


Solution

  • A low-level function like this should not directly add items to a memo. Instead pass a TStrings (an abstraction of a string list) into the function and fill it:

    function CountFilesInFolder(AFolder: String; AMask: String; FileNames: TStrings): Integer;
    begin
    // do your file enumeration
    // for each file call FileNames.Add(FileName);
    end;
    

    Since the Lines property of a memo is also of type TStrings you can use it directly like this:

    CountFilesInFolder('D:\', '*.TXT', Memo1.Lines);
    

    If you wanted to have the filenames in a string list, the usual pattern goes like this:

    FileNames := TStringList.Create;
    try
      CountFilesInFolder('D:\', '*.TXT', FileNames);
    finally
      FileNames.Free;
    end;
    

    The important point is that the caller creates and destroys the TStringList passed into CountFilesInFolder - an important principle in Delphi.