Search code examples
delphitstringgridfilelist

list all files from a directory in a string grid with delphi


I am working with Delphi 7 and I would like to list all the files in a given directory in a string grid (one file per row and all in 1 column). I have searched for about an hour now and cannot find any examples on how to do this so any help you can provide would be appreciated.


Solution

  • This will fill a TStrings descendant (eg., TStringList, TMemo.Lihes, and so forth) with all of the files in a specified folder:

    function  GetFiles(const StartDir: String; const List: TStrings): Boolean;
    var
      SRec: TSearchRec;
      Res: Integer;
    begin
      if not Assigned(List) then
      begin
        Result := False;
        Exit;
      end;
      Res := FindFirst(StartDir + '*.*', faAnyfile, SRec );
      if Res = 0 then
      try
        while res = 0 do
        begin
          if (SRec.Attr and faDirectory <> faDirectory) then
            // If you want filename only, remove "StartDir +" 
            // from next line
            List.Add( StartDir + SRec.Name );
          Res := FindNext(SRec);
        end;
      finally
        FindClose(SRec)
      end;
      Result := (List.Count > 0);
    end;
    

    Use it like this to populate your TStringGrid (Grid in the code below - I added code to auto-size the column based on the length of the longest filename):

    var
      SL: TStringList;
      i: Integer;
      MaxWidth, CurrWidth: Integer;
    const
      Padding = 10;
    begin
      SL := TStringList.Create;
      try
        if GetFiles('C:\Temp\', SL) then
        begin
          MaxWidth := Grid.ColWidths[0];
          for i := 0 to SL.Count - 1 do
          begin
            CurrWidth := Grid.Canvas.TextWidth(SL[i]);
            if CurrWidth > MaxWidth then
              MaxWidth := CurrWidth;
            // Populates first column in stringgrid.
            Grid.RowCount := Grid.RowCount + 1;
            Grid.Cells[0, Grid.RowCount - 1] := SL[i];
          end;
          Grid.ColWidths[0] := MaxWidth + Padding;
        end;
      finally
        SL.Free;
      end;
    end;
    

    Note that this code requires the path to include the trailing backslash after the folder name; you can modify it easily to automatically add it if needed, or to accept both a folder name and a file mask to include only certain files.