e是文件夹路径,Filetpye 是文件类型,Tstr是一个TStrings,用来记录搜索出来的所有文件路径。你需要做的就是调用这个函数,并把Tstr导入到listview中
procedure FindFile(FindFileName:string; Filetpye : string ;Tstr:TStrings);
var
FSearchRec,
DSearchRec: TSearchRec;
FindResult: integer;
function IsDirNotation(ADirName: String): Boolean;
begin
Result := (ADirName = '.') or (ADirName = '..');
end;
begin
if FindFileName[Length(FindFileName)]<> '\' then
FindFileName:=FindFileName+'\';
FindResult := FindFirst(FindFileName+'*.*', faDirectory, DSearchRec);
//tstr.Add(FindFileName+fsearchrec.Name);
while FindResult = 0 do
begin
if ((DSearchRec.Attr and faDirectory) = faDirectory) and not
IsDirNotation(DSearchRec.Name) then
begin
FindFile(FindFileName+DSearchRec.Name,Filetpye,Tstr);
// tstr.Add(FindFileName+fsearchrec.Name);
end;
FindResult := FindNext(DSearchRec);
end;
FindResult := FindFirst(FindFileName+'*.*',faAnyFile+faHidden+
faSysFile,FSearchRec);
// tstr.Add(FindFileName+fsearchrec.Name);
try
while FindResult = 0 do
begin
//ShowMessage(FindFileName+fsearchrec.Name);
if Pos(Filetpye,FindFileName+fsearchrec.Name)>0 then
begin
tstr.Add(FindFileName+fsearchrec.Name);
end;
FindResult := FindNext(FSearchRec);
end;
finally
FindClose(FSearchRec);
end;
Findclose(DSearchRec);
end;
假设搜索G盘的所有文件,存入数据库的 File 表的 Files 字段
procedure TForm1.GetDirsAndFiles(APath: String; AList: TStrings;
HasPath: Boolean);
var
F: TSearchRec;
FileName, RFileName: String;
begin
if FindFirst(APath + '\*.*', faAnyFile, F) = 0 then
repeat
FileName := F.Name;
if (FileName <> '.') and (FileName <> '..') then begin
if HasPath then
RFileName := APath + '\' + FileName
else
RFileName := FileName;
AList.Add(RFileName);
Caption := '搜索-' + RFileName;
if F.Attr and faDirectory <> 0 then
GetDirsAndFiles(APath + '\' + F.Name, AList);
end;
Application.ProcessMessages;
until FindNext(F) <> 0;
FindClose(F);
end;
procedure TForm1.btnSearchClick(Sender: TObject);
var
sList: TStringList;
begin
sList := TStringList.Create;
GetDirsAndFiles('G:',sList);
SaveToDB(sList);
sList.Free;
end;
procedure TForm1.SaveToDB(AList: TStrings);
var
i: Integer;
SQLText,sCount: String;
begin
con.Connected := True;
sCount := IntToStr(AList.Count - 1);
for i := 0 to AList.Count - 1 do begin
SQLText := 'INSERT INTO file (files) VALUES (''' + AList[i] + ''')';
try
with ado do begin
SQL.Text := SQLText;
ExecSQL;
end;
finally
end;
Application.ProcessMessages;
Caption := '存入数据库进度-' + IntToStr(i) + '/' + sCount;
end;
end;