簡體   English   中英

檢查文件擴展名在delphi中是否有效

[英]Check if file extension is valid in delphi

我有一個TEditbox,用戶在其中鍵入文件的某些名稱以及他要另存為的擴展名。 現在,我要驗證他輸入的擴展名是否是在Windows中注冊的有效擴展名。 我該如何實現?

我所擁有的是:

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

如何使用該字符串變量並檢查它是否是在Windows中注冊的有效文件擴展名?

我認為這不是在“破壞”注冊表。 據我所知,如果不從注冊表中讀取任何值,就沒有很好的方法來做您想做的事情。 因此,如果要使用注冊表,請使用以下代碼:

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;

接着:

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

工作正常。 如果擴展名未與有效程序關聯,則返回空字符串。 例如,如果輸入“ doc”(不帶“。”),它將返回Word.Document.8;如果輸入“ abcdef”,則將不返回任何內容('')。

別忘了:將擴展名中不帶點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM