本文整理自网络,侵删。
获取指定目录下所有文件名,这是一个一个目录遍历的方法:
function TPathWatch.FList(ASourFile: string): TStrings; // 查找子目录 AStrings存放查找出路径, ASourceFile要查找的目录
var
sour_path, sour_file: string; // 源路径,源文件名类型
TmpList: TStringList;
FileRec, subFileRec: TSearchrec;
i: Integer;
begin
Result := TStringList.Create; // 在函数内,result是不需要释放的,在调用时,定义的对象已经释放
sour_file := '*.*'; // 任何文件类型 可以自己选择指定的文件类型
if copy(ASourFile, Length(ASourFile), 1) <> '\' then // 在路径后面加上反斜杠
sour_path := IncludeTrailingPathDelimiter(Trim(ASourFile))
else
sour_path := Trim(ASourFile);
if not DirectoryExists(sour_path) then
begin
Result.Clear;
exit;
end;
TmpList := TStringList.Create;
TmpList.Clear;
if FindFirst(sour_path + '*.*', faAnyfile, FileRec) = 0 then
repeat
if ((FileRec.Attr and faDirectory) <> 0) then
begin
if ((FileRec.Name <> '.') and (FileRec.Name <> '..')) then
FList(sour_path);
end;
until FindNext(FileRec) <> 0;
FindClose(FileRec);
if FindFirst(sour_path + sour_file, faAnyfile, subFileRec) = 0 then
repeat
if ((subFileRec.Attr and faDirectory) = 0) then
TmpList.Add(sour_path + subFileRec.Name);
until FindNext(subFileRec) <> 0;
FindClose(subFileRec);
for i := 0 to TmpList.Count - 1 do
Result.Add(TmpList.Strings[i]);
TmpList.Free;
end;
然后在XE下,我发现了更好的方法,上面这种方法一个个循环,看着就很麻烦,在XE中的IOUtils的TDirectory和TFile单元已经帮忙解决了:
procedure TForm2.SpeedButton5Click(Sender: TObject);
var
a: TStringDynArray;
i: Integer;
begin
a:=IOUtils.TDirectory.GetFiles('d:\zzz',TSearchOption.soAllDirectories,nil); // 获取一个目录下所有文件名,包括子目录
for i:=0 to Length(a)-1 do begin
Log(
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;
var
a: TStringDynArray;
i: integer;
begin
result := TStringList.Create;
if TimeState = True then
begin
a := IOUtils.TDirectory.GetFiles(ASourFile,TSearchOption.soAllDirectories,nil); // 获取一个目录下所有文件名,包括子目录
for i := 0 to Length(a)-1 do
result.add(a[i] + ':' + DateTimeToStr(IOUtils.TFile.GetCreationTime(a[i]))); // 文件名 + 创建时间
end else
begin
a := IOUtils.TDirectory.GetFiles(ASourFile,TSearchOption.soAllDirectories,nil); // 获取一个目录下所有文件名,包括子目录
for i := 0 to Length(a)-1 do
result.add(a[i]); // 文件名 + 创建时间
end;
获取文件创建时间: 只到当天
procedure TForm2.SpeedButton4Click(Sender: TObject);
var
DateTime: TDateTime;
begin
FileAge('D:\AAA.txt', DateTime);
ShowMessage(DateTimeToStr(DateTime));
end;
相关阅读 >>
Delphi systemparametersinfo 用法
Delphi的webbrowser改造,对网页中alter等对话框的改造方法
Delphi 简单的操作memo1剪切 复制 粘贴 撤销 全选 清空
Delphi httpclient async异步获取网页代码
更多相关阅读请进入《Delphi》频道 >>