フォルダから指定した拡張子のファイルをListBoxに列挙しようと思い、
ここのBBSに載っていたものを参考にしているのですが、
サブフォルダのファイルまで列挙するには、どのようにすれば出来るのでしょうか?
よろしくお願いします。
参考にしたのは
https://www.petitmonte.com/bbs/answers?question_id=1583
にあるjokさんの物です。
>procedure TForm1.Button1Click(Sender: TObject);
>var
> sr:TSearchRec;
> ret,cnt:integer;
>begin
> cnt := 0;
> ret := FindFirst('C:\*.txt',faAnyFile,sr);
> while ret = 0 do
> begin
> Inc(cnt);
> ListBox1.Items.Add(Format('%.2d %s',[cnt,sr.FindData.cFileName]));
> ret := FindNext(sr);
> end;
> FindClose(sr);
>end;
土日は Res がつきにくいですね。
procedure ListUpFiles(Path, Ext: String; var List: TStringList);
var
SearchRec: TSearchRec;
SearchRes: integer;
Attri: Integer;
begin
Ext := AnsiLowerCase(Ext);
// Pathの最後が'\'でない場合、'\'を加える = 重要
// Delphi5以上では、
// Path := IncludeTrailingBackslash(Path); の1行でよい
if not IsPathDelimiter(Path, Length(Path)) then
Path := Path + '\';
SearchRes := FindFirst(Path + '*', faAnyFile, SearchRec);
try
while SearchRes = 0 do
begin
Attri := SearchRec.Attr and faDirectory;
if (Attri = faDirectory) and (SearchRec.Name <> '.')
and (SearchRec.Name <> '..') then
ListUpFiles(Path + SearchRec.Name, Ext, List) // 再起処理
else
// ターゲットファイルをリストアップ
if AnsiLowerCase(ExtractFileExt(SearchRec.Name)) = Ext then
List.Add(Path + SearchRec.Name);
SearchRes := FindNext(SearchRec);
end;
finally
FindClose(SearchRec);
end;
end;
// Demo
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
List: TStringList;
Path: String;
begin
Path := '???????????';
List := TStringList.Create;
ListUpFiles(Path, '.txt', List);
Label1.Caption := '検索終了; 集計数' + IntToStr(List.Count);
for i := 0 to List.Count - 1 do
Memo1.Lines.Add(List.Strings[i]);
end;
sadoyamaさんのプログラムで無事目標を達成できました。
Demoまで書いていただいて、本当にありがとうございました!
ツイート | ![]() |