Search a file in all subdirecrories(50分)

  • 主题发起人 主题发起人 cmtan
  • 开始时间 开始时间
C

cmtan

Unregistered / Unconfirmed
GUEST, unregistred user!
SeaechFile Fuction only searches a file in the defined directory.

How can I search a file in the defined directory and all its
subdirectories?

Thanks in advance.

 
以下为查找指定文件的例程,放一个Button执行查找,放一个ListBox显示
查找结果。

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, FileCtrl;

type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

{---------------------------------------
文件查找函数 SearchFile

参数说明:
sFileName: 要查找的文件名称
sRootDir: 指定在哪个目录中查找
bFileOnly: 是否只查找文件
bRecurse: 是否查找子目录

返回值:
FileList: 查找结果列表
----------------------------------------}
function SearchFile(sFileName, sRootDir: string;
bFileOnly, bRecurse: boolean): TStringList;
//内嵌文件查找递归过程
procedure DoSearchFile(sFileName, sRootDir: string;
bFileOnly, bRecurse: boolean;
var FileList: TStringList);
var
Found: integer;
SearchRec: TSearchRec;
begin
//开始查找
Found := FindFirst(sRootDir + '/*.*', faAnyFile, SearchRec);
while Found = 0 do
begin
//遇到子目录时确定是否查找子目录和是否将符合条件的子目录加入查找结果
if (SearchRec.Attr = faDirectory) and (SearchRec.Name <> '.') and
(SearchRec.Name <> '..') then
begin
if (AnsiCompareText(sFileName, SearchRec.Name) = 0) and not bFileOnly then
FileList.Add(sRootDir + '/' + SearchRec.Name);
if bRecurse then
DoSearchFile(sFileName, sRootDir + '/' + SearchRec.Name, bFileOnly, bRecurse, FileList);
end
//找到符合条件的文件时加入查找结果
else if AnsiCompareText(sFileName, SearchRec.Name) = 0 then
FileList.Add(sRootDir + '/' + SearchRec.Name);
Found := FindNext(SearchRec);
end;
FindClose(SearchRec);
end;
var
FileList: TStringList;
begin
FileList := TStringList.Create;
FileList.Clear;
DoSearchFile(sFileName, sRootDir, bFileOnly, bRecurse, FileList);
Result := FileList;
end;

procedure TForm1.Button1Click(Sender: TObject);
{按Button时进行查找,结果显示到ListBox中}
begin
ListBox1.Items.Assign(SearchFile('Project1.dpr', 'd:/', True, True));
end;

end.
 

Similar threads

A
回复
0
查看
619
Andreas Hausladen
A
A
回复
0
查看
943
Andreas Hausladen
A
A
回复
0
查看
819
Andreas Hausladen
A
A
回复
0
查看
478
Andreas Hausladen
A
后退
顶部