如何将多个文件扩展名传递给TDirectory.GetFiles? [英] How to pass multiple file extensions to TDirectory.GetFiles?
问题描述
TDirectory.GetFiles
有一个参数叫做 SearchPattern
。 Embarcadero的文档说
TDirectory.GetFiles
has a parameter called SearchPattern
. Embarcadero's documentation says
匹配文件名时使用的掩码(例如,* .exe匹配所有可执行文件)。
The mask used when matching file names (for example, "*.exe" matches all the executable files).
但是,我想传递多种文件类型。我从一个 FilterComboBox.Mask
中获取这些类型。所以,它是一个看起来像'*。txt; *。rtf; *。doc'
的字符串。
However, I want to pass multiple file types. I get those types from a FilterComboBox.Mask
. So, it is a string that looks like '*.txt;*.rtf;*.doc'
.
我已经尝试将该字符串直接传递给 GetFiles
,它不起作用。我必须解析它,把它分成几块,然后把每个单独的一块送到 GetFiles
?
I have tried to pass that string directly to GetFiles
and it doesn't work. Do I have to parse it, break it into pieces and feed every individual piece to GetFiles
?
推荐答案
GetFiles
后面的RTL代码调用 Masks.MatchesMask
来测试匹配您的搜索模式。此功能仅支持对单个掩码进行掩码。
The RTL code behind GetFiles
calls Masks.MatchesMask
to test for a match to your search pattern. This function only supports masking against a single mask.
另一种方法是使用 GetFiles
重载, code> TFilterPredicate 。您提供一个测试名称是否符合您的模式的谓词。
The alternative is to use the GetFiles
overload that admits a TFilterPredicate
. You supply a predicate that tests whether or not a name matches your pattern.
uses
StrUtils, Types, Masks, IOUtils;
function MyGetFiles(const Path, Masks: string): TStringDynArray;
var
MaskArray: TStringDynArray;
Predicate: TDirectory.TFilterPredicate;
begin
MaskArray := SplitString(Masks, ';');
Predicate :=
function(const Path: string; const SearchRec: TSearchRec): Boolean
var
Mask: string;
begin
for Mask in MaskArray do
if MatchesMask(SearchRec.Name, Mask) then
exit(True);
exit(False);
end;
Result := TDirectory.GetFiles(Path, Predicate);
end;
请注意, MatchesMask
创建并销毁每次都分配了 TMask
叫。我可以想象,作为长期搜索的表现瓶颈。在这种情况下,您可以从 MaskArray
创建一个 TMask
对象的数组。并使用谓词中的那些来测试。我不知道这是否是一个有效的关注,只是我在阅读代码时发生的情况。
Do note that MatchesMask
creates and destroys a heap allocated TMask
every time it is called. I can well imagine that being a performance bottleneck over a long search. In which case you could create an array of TMask
objects from MaskArray
. And use those in the predicate to test. I've no idea whether this is a valid concern or not, just something that occurred to me whilst perusing the code.
这篇关于如何将多个文件扩展名传递给TDirectory.GetFiles?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!