delphi中查找指定文件的例程

代码如下:

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.


你可能感兴趣的:(Delphi代码类)