问题
TDirectory.GetFiles has a parameter called SearchPattern. Embarcadero's documentation says
The mask used when matching file names (for example, "*.exe" matches all the executable files).
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'.
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?
回答1:
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.
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;
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.
来源:https://stackoverflow.com/questions/12726756/how-to-pass-multiple-file-extensions-to-tdirectory-getfiles