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 转换一批.bmp 文件为 .jpg

Delphi 文件分割合并

Delphi dll窗体调用解

Delphi ifileoperation替换shfileoperation

Delphi psafearray与tbytes类型转换

Delphi 让socket支持域名上线

怎样在Delphi中屏蔽flash控件的右键弹出菜单

Delphi trestclient + trestrequest + trestresponse

Delphi中用tlistview显示数据库数据

Delphi 中相对路径与绝对路径函数说明

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...