Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file extension is valid in delphi

Tags:

delphi

I have a TEditbox where the user keys in some name for the file along with the extension he wants to save it as. Now I want to validate if the extension he entered is a valid extension registered with windows. How can I achieve this?

All I have is:

procedure TForm2.OkBtnClick(Sender: TObject);
var
ExtractedFileExt: string;
begin
  ExtractedFileExt := ExtractFileExt(cxCbxSelectedFile.Text);
end;

How can I use that string variable and check if it is a valid file extension registered with Windows?

like image 857
Hello Man Avatar asked Feb 02 '26 09:02

Hello Man


1 Answers

I think it's not "hacking" the registry. As far as I know, there is no good way to do what you want to do without reading any values from the registry. So, use this code if you want to use the registry:

uses Registry;

function GetProgramAssociation(const Ext: string): string;
var reg: TRegistry;
    s: string;
begin
  s:='';
  reg:=TRegistry.Create;
  try
    reg.RootKey:=HKEY_CLASSES_ROOT;
    if reg.OpenKey('.'+ext+'shellopencommand', false) then
    begin
      s:=reg.ReadString('');
      reg.CloseKey;
    end
    else
    begin
      if reg.OpenKey('.'+ext, false) then
      begin
        s:=reg.ReadString('');
        reg.CloseKey;
        if s='' then
        begin
          if reg.OpenKey(s+'shellopencommand', false) then
            s:=reg.ReadString('');
          reg.CloseKey;
        end;
      end;
    end;
    if Pos('%', s) > 0 then Delete(s, Pos('%', s), length(s));
    if ((length(s)>0) and (s[1]='"')) then Delete (s, 1, 1);
    if ((length(s)>0) and (s[length(s)]='"')) then Delete(s, Length(s), 1);
    while ((length(s)>0) and ((s[length(s)]=#32) or (s[length(s)]='"'))) do
      Delete(s, Length(s), 1);
    result:=s;
  finally
  reg.Free;
  end;
end;

And then:

if GetProgramAssociation(Extension) = '' then
  ShowMessage('Nope!');

It works fine. It returns an empty string if the Extension is not associated with a valid program. For example if you enter 'doc' (without '.') it returns Word.Document.8 and if you enter 'abcdef' it returns nothing ('').

Don't forget: put in the extension without a dot

like image 178
renehsz Avatar answered Feb 05 '26 03:02

renehsz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!