使用delphi列出字符串网格中目录中的所有文件

时间:2012-07-15 05:31:57

标签: delphi tstringgrid filelist

我正在使用Delphi 7,我希望在字符串网格中列出给定目录中的所有文件(每行一个文件,1列中全部)。我现在已经搜索了大约一个小时,找不到任何关于如何做到这一点的例子,所以你能提供任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:7)

这将填充TStrings后代(例如,TStringListTMemo.Lihes等等)以及指定文件夹中的所有文件:

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;

像这样使用它来填充TStringGrid(下面代码中的Grid - 我添加了代码以根据最长文件名的长度自动调整列的大小):

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;

请注意,此代码需要在文件夹名称后包含尾部反斜杠的路径;您可以轻松地修改它以在需要时自动添加它,或接受文件夹名称和文件掩码以仅包含某些文件。

答案 1 :(得分:0)

  1. 使用SysUtil.FindFirst/FindNext/FindClose获取文件

  2. 只需将字符串插入所需的行/列即可。根据需要增加“RowCount”: