Search code examples
delphidelphi-2010

How do you set the FileTypeIndex in a DoExecute TFileSaveDialog Event if the extension is known?


If a file extension is known how do you convert the extension to a FileTypeIndex in the TFileSaveDialog DoExecute event?

   function TIEWin7FileSaveDialog.DoExecute: Bool;
    begin
    ...
    {Set FileType (filter) index}
    iWideTextension := ExtractFileExt(FileName);
    FileTypeIndex := ???ExtensionToFileTypeIndex(iWideExtension);???
    FileDialog.SetFileTypeIndex(FileTypeIndex);
    ...
    end;

Solution

  • There's no explicit function that would do what you want at least since one file type may be contained in more file type masks, so you can only iterate the FileTypes and check if the file type is contained or equals to the FileMask like shown below:

    function FindFirstFileType(FileDialog: TCustomFileDialog;
      const FileExt: string): UINT;
    var
      TypeIndex: Integer;
      ExtIndex: Integer;
      ExtArray: TStringDynArray;
    begin
      Result := 0;
      for TypeIndex := 0 to FileDialog.FileTypes.Count - 1 do
      begin
        ExtArray := SplitString(FileDialog.FileTypes[TypeIndex].FileMask, ';');
        for ExtIndex := 0 to High(ExtArray) do
          if ExtArray[ExtIndex] = FileExt then
            begin
              Result := TypeIndex;
              Break;
            end;
      end;
    end;
    

    And the usage (note that the input must match exactly to the filter mask):

    procedure TForm1.Button1Click(Sender: TObject);
    var
      I: UINT;
    begin
      I := FindFirstFileType(FileOpenDialog1, '*.pas');
    end;