【问题标题】:list all files from a directory in a string grid with delphi使用delphi列出字符串网格中目录中的所有文件
【发布时间】:2012-07-14 10:29:36
【问题描述】:

我正在使用 Delphi 7,我想在字符串网格中列出给定目录中的所有文件(每行一个文件,全部在 1 列中)。我已经搜索了大约一个小时,但找不到任何有关如何执行此操作的示例,因此您可以提供任何帮助,我们将不胜感激。

【问题讨论】:

    标签: delphi tstringgrid filelist


    【解决方案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;
    

    像这样使用它来填充您的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;
    

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

    【讨论】:

    • 这似乎列出了文件夹而不是文件,或者我做错了什么。
    • 你错过了我的编辑。 :-) 将= faDirectory 更改为&lt;&gt; faDirectory
    【解决方案2】:
    1. 使用SysUtil.FindFirst/FindNext/FindClose获取文件

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 2017-02-16
      • 2011-06-13
      • 2012-12-23
      • 1970-01-01
      • 2012-03-31
      相关资源
      最近更新 更多