delphi 搜索文件夹_如何使用Delphi搜索文件和文件夹

delphi 搜索文件夹

When looking for files, it is often useful and necessary to search through subfolders. Here, see how to use Delphi's strength to create a simple, but powerful, find-all-matching-files project.

查找文件时,通常在子文件夹中搜索很有用且必要。 在这里,了解如何使用Delphi的优势来创建一个简单但功能强大的“查找所有匹配文件”项目。

文件/文件夹蒙版搜索项目 ( File/Folder Mask Search Project )

The following project not only lets you search for files through subfolders, but it also lets you easily determine file attributes, such as Name, Size, Modification Date, etc. so you can see when to invoke the File Properties Dialog from the Windows Explorer. In particular, it demonstrates how to recursively search through subfolders and assemble a list of files that match a certain file mask. The technique of recursion is defined as a routine that calls itself in the middle of its code.

以下项目不仅使您可以通过子文件夹搜索文件,而且还可以轻松确定文件属性,例如名称,大小,修改日期等,以便您可以看到何时从Windows资源管理器调用“文件属性”对话框。 特别是,它演示了如何递归搜索子文件夹并组合与某个文件掩码匹配的文件列表。 递归技术定义为在其代码中间调用自身的例程。

In order to understand the code in the project, we have to familiarize ourselves with the next three methods defined in the SysUtils unit: FindFirst, FindNext, and FindClose.

为了理解项目中的代码,我们必须熟悉SysUtils单元中定义的以下三种方法:FindFirst,FindNext和FindClose。

FindFirst ( FindFirst )

FindFirst is the initialization call to start a detailed file search procedure using Windows API calls. The search looks for files that match the Path specifier. The Path usually includes wildcard characters (* and ?). Attr parameter contains combinations of file attributes to control the search. The file attribute constants recognized in Attr are: faAnyFile (any file), faDirectory (directories), faReadOnly (read only files), faHidden (hidden files), faArchive (archive files), faSysFile (system files) and faVolumeID (volume ID files).

FindFirst是初始化调用,用于使用Windows API调用启动详细的文件搜索过程。 搜索将查找与路径说明符匹配的文件。 路径通常包含通配符(*和?)。 Attr参数包含文件属性的组合以控制搜索。 Attr中识别的文件属性常量是: faAnyFile (任何文件), faDirectory (目录), faReadOnly (只读文件), faHidden (隐藏文件),faArchive(存档文件), faSysFile (系统文件)和faVolumeID (卷ID文件) )。

If FindFirst finds one or more matching files it returns 0 (or an error code for failure, usually 18) and fills in the Rec with information about the first matching file. In order to continue the search, we have to use the same TSearcRec record and pass it to the FindNext function. When the search is completed the FindClose procedure must be called to free internal Windows resources. The TSearchRec is a record defined as:

如果FindFirst找到一个或多个匹配文件,则返回0(或失败的错误代码,通常为18),并在Rec中填充有关第一个匹配文件的信息。 为了继续搜索,我们必须使用相同的TSearcRec记录并将其传递给FindNext函数。 搜索完成后,必须调用FindClose过程以释放内部Windows资源。 TSearchRec是一条记录,定义为:

When the first file is found the Rec parameter is filled, and the following fields (values) can be used by your project.. Attr, the file's attributes as described above.. Name holds a string that represents a file name, without path information. Size in bytes of the file found.. Time stores the file's modification date and time as a file date.. FindData contains additional information such as the file creation time, last access time, and both the long and short file names.

当第一个文件被发现录制参数被填满,和下面的字段(值)可以通过你的项目.. 的Attr,如上所述.. 姓名认为表示文件名的字符串文件的属性被使用,不带路径信息。 找到的文件大小(以字节为单位)。 时间存储文件的修改日期和时间作为文件日期。FindData包含其他信息,例如文件创建时间,上次访问时间以及长文件名和短文件名。

找下一个 ( FindNext )

The FindNext function is the second step in the detailed file search procedure. You have to pass the same search record (Rec) that has been created by the call to FindFirst. The return value from FindNext is zero for success or an error code for any error.

FindNext函数是详细文件搜索过程中的第二步。 您必须传递通过调用FindFirst创建的相同搜索记录(Rec)。 FindNext的返回值表示成功则为零,如果有任何错误则返回错误码。

查找关闭 ( FindClose )

This procedure is the required termination call for a FindFirst/FindNext.

此过程是FindFirst / FindNext所需的终止调用。

在Delphi中进行递归文件掩码匹配搜索 ( Recursive File Mask Matching Searching in Delphi )

This is the "Searching for files" project as it appears at run time. The most important components on the form are two edit boxes, one list box, a checkbox and a button. Edit boxes are used to specify the path you want to search in and a file mask. Found files are displayed in the List box and if the checkbox is checked then all subfolders are scanned for matching files.

这是在运行时出现的“搜索文件”项目。 表单上最重要的组件是两个编辑框,一个列表框,一个复选框和一个按钮。 编辑框用于指定要搜索的路径和文件掩码。 找到的文件显示在“列表”框中,如果选中该复选框,则将扫描所有子文件夹以查找匹配的文件。

Below is the small code snippet from the project, just to show that searching for files with Delphi is as easy as can be:

下面是该项目中的一小段代码,只是为了说明使用Delphi搜索文件非常容易:

翻译自: https://www.thoughtco.com/search-for-files-and-folders-matching-a-mask-1058391

delphi 搜索文件夹

搜索TXT 文件的示例unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls; type TForm1 = class(TForm) ListBox1: TListBox; Memo2: TMemo; Panel1: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Edit1: TEdit; ButtonSearchFile: TButton; FolderPath: TEdit; FileExt: TEdit; ProgressBar1: TProgressBar; procedure ButtonSearchFileClick(Sender: TObject); procedure ListBox1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure SearchFile1(FileName: string; FindText: string); function MakeFileList(Path, FileExt: string): TStringList; function FileInUsed(FileName: TFileName): Boolean; public { Public declarations } end; var Form1: TForm1; implementation uses StrUtils; {$R *.dfm} { Search Options KeyWord in file FileName FileSize FileCreateTime FileModifyTime keyword filepath openfile found addListbox } var FileNamePathList, FileNameList: TStringList; procedure TForm1.FormCreate(Sender: TObject); begin FileNameList := TStringList.Create; FileNamePathList := TStringList.Create; end; { if FileInUsed ('D:\Administrator\Documents\MyProjects\FileSearch\Win32\Debug\Project1.exe') then ShowMessage('File is in use.') else ShowMessage('File not in use.'); } function TForm1.FileInUsed(FileName: TFileName): Boolean; var HFileRes: HFILE; begin Result := False; if not FileExists(FileName) then Exit; // 如果文件不存在,返回false HFileRes := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); Result := (HFileRes = INVALID_HANDLE_VALUE); if not Result then CloseHandle(HFileRes); end; procedure TForm1.SearchFile1(FileName: string; FindText: string); var SearchList: TStringList; begin try SearchList := TStringList.Create; if FileExists(FileName) and (not FileInUsed(FileName)) then begin SearchList.LoadFromFile(FileName); if Boolean(Pos(UpperCase(FindText), UpperCase(SearchList.Text))) then begin FileNameList.Add(ExtractFileName(FileName)); FileNamePathList.Add(FileName); end; end; finally SearchList.Free; end; end; procedure TForm1.ButtonSearchFileClick(Sender: TObject); var I, n: Integer; List: TStringList; begin try ButtonSearchFile.Caption := 'SearchFile'; List := TStringList.Create; List.Clear; FileNameList.Clear; FileNamePathList.Clear; List := MakeFileList(FolderPath.Text, FileExt.Text); ProgressBar1.Max := List.Count; for I := 0 to List.Count - 1 do begin Application.ProcessMessages; SearchFile1(List[I], Edit1.Text); ProgressBar1.Position := I; end; ListBox1.Items.Text := FileNameList.Text; ButtonSearchFile.Caption := IntToStr(FileNamePathList.Count) + ' 条'; finally List.Free; end; end; { 这个过程得显示进度 } function TForm1.MakeFileList(Path, FileExt: string): TStringList; var sch: TSearchrec; begin Result := TStringList.Create; if RightStr(Trim(Path), 1) '\' then Path := Trim(Path) + '\' else Path := Trim(Path); if not DirectoryExists(Path) then begin Result.Clear; Exit; end; if FindFirst(Path + '*', faAnyfile, sch) = 0 then begin repeat Application.ProcessMessages; if ((sch.Name = '.') or (sch.Name = '..')) then Continue; if DirectoryExists(Path + sch.Name) then begin Result.AddStrings(MakeFileList(Path + sch.Name, FileExt)); end else begin if (UpperCase(ExtractFileExt(Path + sch.Name)) = UpperCase(FileExt)) or (FileExt = '.*') then Result.Add(Path + sch.Name); end; until FindNext(sch) 0; FindClose(sch); end; end; procedure TForm1.ListBox1Click(Sender: TObject); var s: string; txt: string; begin if not FileExists(FileNamePathList[ListBox1.ItemIndex]) then Exit; Memo2.Lines.LoadFromFile(FileNamePathList[ListBox1.ItemIndex]); Caption := FileNamePathList[ListBox1.ItemIndex]; txt := Form1.Memo2.Text; if Boolean(Pos(UpperCase(Edit1.Text), UpperCase(txt))) then begin Memo2.SetFocus; Memo2.SelStart := Pos(UpperCase(Edit1.Text), UpperCase(txt)) - 1; Memo2.SelLength := Length(Edit1.Text); end; end; end.
文件搜索控件 TEasyFileSearch v1.02 by Alexandre GAMBIER Read versions.txt file if you want to see modifications made between each version. Thanks ------ Thanks to : - Udo for his tests on C++ Builder 5 and his ideas for v1.01, v1.02 - J.M. Fontaine for his test on Delphi 7 and his orthography help for v1.01. 1 - DESCRIPTION --------------- TEasyFileSearch is freeware and you use it at your own risk. TEasyFileSearch is completely free also for commercial use. TEasyFileSearch is a component which enable you to search file or folder in directory and subdirectory, using filter mask (*.*, *.exe, ...). You define some search criteria : - look in subfolder , - look for readonly file , - look for hidden file , - look for system file , - look for archile file , - look for directory file, - look for anyfile file . You can filter your research - look for files that is smaller or equal to a size, - look for files that is bigger or equal to a size, - look for file than date is between two date, younger, older or the same than a date, - look for created, modified or opened files. You can exclude files using filter mask, for example you can exclude all files *.exe. TEasyFileSearch don't use recursive function (no stack owerflow error). 2 - LANGUAGE/OS --------------- TEasyFileSearch has been tested only on Delphi 5, 7 and C++ Builder 5. 3 - INSTALLATION ---------------- 1. Extract the TEasyFileSearch.zip 2. Choose Component|Install Component... from the menu 3. Select the Tab 'Into New Package' and fill in: At 'Unit file name': Browse and Select EasyFileSearchReg.pas from the directory where you installed it. At 'Package file name': TEasyFileSearch ( In the directory Projects\Lib ) At 'Description': TEasyFileSearch - looking for files Select Ok 4. You will be asked to confirm building the packag
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值