こんにちは。
> いつもお世話になります。
> 下記コードだと、二階層上のフォルダが 隠し属性な場合、列挙されてしまう気がするのです。
確かにそうですね。
そうなると理屈上 "検索は (ドライブ) ルートフォルダから行わなくてはならない" という事になってしま
いますので、
function EnumFiles_WithOutHidden(const Path: string; SearchPattern: string): TStringDynArray;
var
FA: TFileAttributes;
dPath, dCPath, PathRoot: string;
Hidden_Flg: Boolean;
HiddenList, PathList: TStringDynArray;
begin
// 配列を初期化
SetLength(result, 0);
// 絶対パスを生成
if TPath.IsRelativePath(Path) then
dPath := TPath.GetFullPath(Path)
else
dPath := ExcludeTrailingPathDelimiter(Path);
// 上の階層のフォルダを検索
Hidden_Flg := False;
PathRoot := ExcludeTrailingPathDelimiter(TPath.GetPathRoot(dPath));
dCPath := dPath;
repeat
FA := TDirectory.GetAttributes(dCPath);
if (TFileAttribute.faHidden in FA) then
begin
Hidden_Flg:= True;
Break;
end;
dCPath := TPath.GetDirectoryName(dCPath + '.a');
until ((dCPath) <> PathRoot);
// 指定フォルダが隠し属性フォルダ内だったら抜ける
if Hidden_Flg then
Exit;
// 指定パス以下の隠しフォルダを列挙
HiddenList := TDirectory.GetDirectories(dPath, '*.*', TSearchOption.soAllDirectories,
function (const Path: string; const SearchRec: TSearchRec): Boolean
begin
result := ((faHidden and SearchRec.Attr) > 0);
end);
// 隠しフォルダ内のフォルダは隠しフォルダとみなす
PathList := TDirectory.GetDirectories(dPath, '*.*', TSearchOption.soAllDirectories,
function (const Path: string; const SearchRec: TSearchRec): Boolean
var
l: Integer;
begin
result := ((faHidden and SearchRec.Attr) > 0);
if result then
Exit;
for l:=Low(HiddenList) to High(HiddenList) do
begin
if Pos(HiddenList[l], Path) = 1 then
begin
result := True;
break;
end;
end;
end);
// 指定パス以下のファイルを列挙
result := TDirectory.GetFiles(dPath, SearchPattern, TSearchOption.soAllDirectories,
function (const Path: string; const SearchRec: TSearchRec): Boolean
begin
result := ((faHidden and SearchRec.Attr) = 0) and
(IndexText(Path, PathList) = -1);
end);
end;
こんな事になるかと思います。使い方は次の通りです。
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
Files: TStringDynArray;
begin
Files := EnumFiles_WithOutHidden('C:\TEST', '*.*');
for i:=Low(Files) to High(Files) do
Memo1.Lines.Add(Files[i]);
end;
あまり検索効率がいいとは思えませんが "TDirectory.GetFiles 縛り" という事で参考までに。
(FindFirst / FindNext / FindClose の再帰で書いたほうがスッキリすると思います)
アイテムたくさん☆freemlのプロフィール画像をアバターに♪
http://ad.freeml.com/cgi-bin/sa.cgi?id=jwzMU
------------------------------------------------------[freeml byGMO]--