列出一串电网用delphi从目录中的所有文件(list all files from a direc

2019-10-17 00:45发布

我用Delphi 7工作,我想列出一个字符串格在指定目录中的所有文件(每行都是一个文件中的1列)。 我已经搜索了大约一个小时,现在无法找到如何做到这一点,因此任何帮助,您可以提供将不胜感激任何例子。

Answer 1:

这将填补一个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;

这样使用它来填充TStringGridGrid下面的代码-我的代码添加到自动调整大小基于列的最长文件名长度):

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;

请注意,此代码需要的路径,包括文件夹名称后尾随反斜线; 您可以轻松地修改它,如果需要自动添加,或接受两个文件夹名称和文件掩码只包括某些文件。



Answer 2:

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

  2. 只需插入在所需的行/列的字符串。 根据需要增加“行数”:

    • 添加行

    • 插入/删除行

    • 拉撒路字符串网格引用(好消息,但显著差异德尔福)



文章来源: list all files from a directory in a string grid with delphi