更新: 正如@ David Heffernan 在下面的评论中所提到的, FilterIndex
并不总是匹配实际的文件扩展名; 所以您应该不使用 < code> FilterIndex 来确定文件类型。 因此, 您必须提取文件扩展名并使用它 。
您可以定义已知的文件类型计数, 如 :
TKnowFiles = (kfUnknown, kfJpg, kfTif, ...)
您也可以定义他们的名字,比如
const FilterNames = array[TKnownFiles] of string = ( Any file , ...);
then you can use RTTI functions getEnumName/getEnumValue
to convert kfJpg
to string representation and build Filter
string at runtime.
also using enumeration allows you to easily maintain and extend your code (what if you have to insert BMP files between tif and docx next week? docx, doc,pdf becoome 4,5,6 instead of 3,4,5 and you sould edit your code. )
one of possible solutions is:
type
TKnownFileTypes = (kftUnknown, kftJpg, kftTif, kftDocx, kftDoc, kftPdf);
const
FileFilterNames : array[TKnownFileTypes] of string = (
Alle filer ,
Indscannet fil ,
Indscannet fil ,
Word 2007 dokument ,
Word 2003 dokument ,
PDF fil );
procedure TForm4.Button1Click(Sender: TObject);
const KnownFiles = [low(TKnownFileTypes) .. high(TKnownFileTypes)];
var filterString : string;
fext : string;
kf : TKnownFileTypes;
kfs : string;
resultFileType : TKnownFileTypes;
begin
for kf in KnownFiles - [kftUnknown] do begin
kfs := getEnumName(typeinfo(TKnownFileTypes), ord(kf));
Delete(kfs, 1, 3);
LowerCase(kfs);
FilterString := FilterString +
Format( %s (*.%s)|*.%s| , [FileFilterNames[kf], kfs, kfs]);
end;
FilterString := FilterString + Format( %s (*.*)|*.* , [FileFilterNames[kftUnknown]]);
OpenDialog1.Filter := FilterString;
if not OpenDialog1.Execute() then exit;
fext := ExtractFileExt(OpenDialog1.FileName);
Delete(fext, 1,1); //delete .dot
fext := kft + fExt;
resultFileType := kftUnknown;
for kf in KnownFiles - [kftUnknown] do begin
kfs := getEnumName(typeinfo(TKnownFileTypes), ord(kf));
kfs := LowerCase(kfs);
if kfs <> fext then continue;
resultFileType := kf;
end;
ShowMessage(Format( File Type: %s , [FileFilterNames[resultFileType]]));
end;