简体   繁体   English

检查文件扩展名在delphi中是否有效

[英]Check if file extension is valid in 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. 我有一个TEditbox,用户在其中键入文件的某些名称以及他要另存为的扩展名。 Now I want to validate if the extension he entered is a valid extension registered with windows. 现在,我要验证他输入的扩展名是否是在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? 如何使用该字符串变量并检查它是否是在Windows中注册的有效文件扩展名?

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 (''). 例如,如果输入“ doc”(不带“。”),它将返回Word.Document.8;如果输入“ abcdef”,则将不返回任何内容('')。

Don't forget: put in the extension without a dot 别忘了:将扩展名中不带点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM