1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 获取指定目录下的所有文件名 包括子目录函数

获取指定目录下的所有文件名 包括子目录函数

时间:2021-09-24 07:53:56

相关推荐

获取指定目录下的所有文件名 包括子目录函数

获取指定目录下所有文件名,这是一个一个目录遍历的方法:

function TPathWatch.FList(ASourFile: string): TStrings; // 查找子目录 AStrings存放查找出路径, ASourceFile要查找的目录varsour_path, sour_file: string; // 源路径,源文件名类型TmpList: TStringList;FileRec, subFileRec: TSearchrec;i: Integer;beginResult := TStringList.Create; // 在函数内,result是不需要释放的,在调用时,定义的对象已经释放sour_file := '*.*'; // 任何文件类型 可以自己选择指定的文件类型if copy(ASourFile, Length(ASourFile), 1) <> '\' then// 在路径后面加上反斜杠sour_path := IncludeTrailingPathDelimiter(Trim(ASourFile)) elsesour_path := Trim(ASourFile);if not DirectoryExists(sour_path) thenbeginResult.Clear;exit;end;TmpList := TStringList.Create;TmpList.Clear;if FindFirst(sour_path + '*.*', faAnyfile, FileRec) = 0 thenrepeatif ((FileRec.Attr and faDirectory) <> 0) thenbeginif ((FileRec.Name <> '.') and (FileRec.Name <> '..')) thenFList(sour_path);end;until FindNext(FileRec) <> 0;FindClose(FileRec);if FindFirst(sour_path + sour_file, faAnyfile, subFileRec) = 0 thenrepeatif ((subFileRec.Attr and faDirectory) = 0) thenTmpList.Add(sour_path + subFileRec.Name);until FindNext(subFileRec) <> 0;FindClose(subFileRec);for i := 0 to TmpList.Count - 1 doResult.Add(TmpList.Strings[i]);TmpList.Free;end;

然后在XE下,我发现了更好的方法,上面这种方法一个个循环,看着就很麻烦,在XE中的IOUtils的TDirectory和TFile单元已经帮忙解决了:

procedure TForm2.SpeedButton5Click(Sender: TObject);vara: TStringDynArray;i: Integer;begina:=IOUtils.TDirectory.GetFiles('d:\zzz',TSearchOption.soAllDirectories,nil); // 获取一个目录下所有文件名,包括子目录for i:=0 to Length(a)-1 do beginLog(a[i]+' '+'GetCreationTime:' +DateTimeToStr(IOUtils.TFile.GetCreationTime (a[i]))+ ' ' +'GetLastAccessTime:'+DateTimeToStr(IOUtils.TFile.GetLastAccessTime(a[i]))+ ' ' +'GetLastWriteTime:' +DateTimeToStr(IOUtils.TFile.GetLastWriteTime (a[i]))+ ' ' +' ');end;end;

写成函数,返回值为TStrings,可带时间戳,可不带

function FList(ASourFile: string; TimeState: Boolean = False): TStrings;vara: TStringDynArray;i: integer;beginresult := TStringList.Create;if TimeState = True then begina := IOUtils.TDirectory.GetFiles(ASourFile,TSearchOption.soAllDirectories,nil); // 获取一个目录下所有文件名,包括子目录for i := 0 to Length(a)-1 doresult.add(a[i] + ':' + DateTimeToStr(IOUtils.TFile.GetCreationTime(a[i]))); // 文件名 + 创建时间end elsebegina := IOUtils.TDirectory.GetFiles(ASourFile,TSearchOption.soAllDirectories,nil); // 获取一个目录下所有文件名,包括子目录for i := 0 to Length(a)-1 doresult.add(a[i]); // 文件名 + 创建时间end;

获取文件创建时间: 只到当天

procedure TForm2.SpeedButton4Click(Sender: TObject);varDateTime: TDateTime;beginFileAge('D:\AAA.txt', DateTime);ShowMessage(DateTimeToStr(DateTime));end;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。