使用delphi在字符串网格中列出目录中的所有文件 [英] list all files from a directory in a string grid with delphi
问题描述
我正在使用Delphi 7,我想在字符串网格中列出给定目录中的所有文件(每行一个文件,一列所有).我已经搜索了大约一个小时,但找不到任何有关如何执行此操作的示例,因此,您能提供的任何帮助将不胜感激.
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.
推荐答案
这将填充 TStrings
后代(例如, TStringList
, TMemo.Lihes
,依此类推),并将所有文件都放在指定的文件夹中:
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;
使用它来填充您的 TStringGrid
(下面的代码中的 Grid
-我添加了代码以根据最长文件名的长度自动调整列的大小):
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.
这篇关于使用delphi在字符串网格中列出目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!