How to get the file type description for a file

posted 13 Mar 2010, 18:02 by Delphi Basics
Example:
.rar returns "WinRAR archive"
.txt returns "Text Document"
and
.png returns "PNG Image".

function GetFileTypeDescription(FileName: String): String;
function GetFileTypeRegKey(FileName: String; out Key: HKEY): Integer;


function GetFileTypeDescription(FileName: String): String;
var hkExtType: HKEY;
     lpszDesc: Array [0..1024] of Char;
     dwSize: DWORD;
begin

  // Attempt to get the registry key for the extension type
  if (GetFileTypeRegKey(FileName, hkExtType) = ERROR_SUCCESS) then
  begin
     // Resource protection
     try
        // Set size of buffer
        dwSize:=SizeOf(lpszDesc);
        // Get the description for the file extension
        if (RegQueryValueEx(hkExtType, nil, nil, nil, @lpszDesc, @dwSize) = ERROR_SUCCESS) then
           // Return the description
           SetString(result, PChar(@lpszDesc), dwSize)
        else
           // Failed to get result
           SetLength(result, 0);
     finally
        // Close the registry key
        RegCloseKey(hkExtType);
     end;
  end
  else
     // Failed to get result
     SetLength(result, 0);

end;

function GetFileTypeRegKey(FileName: String; out Key: HKEY): Integer;
var hkExt: HKEY;
     lpszTypeKey: Array [0..1024] of Char;
     dwSize: DWORD;
     szExt: String;
begin

  // Get the file extension
  szExt:=ExtractFileExt(FileName);

  // Attempt to open the registry key
  result:=RegOpenKeyEx(HKEY_CLASSES_ROOT, PChar(szExt), 0, KEY_READ, hkExt);

  // Check result of open
  if (result = ERROR_SUCCESS) then
  begin
     // Resource protection
     try
        // Set size of buffer
        dwSize:=SizeOf(lpszTypeKey);
        // Query for the default value which is the redirect to the extension type key
        result:=RegQueryValueEx(hkExt, nil, nil, nil, @lpszTypeKey, @dwSize);
        // Check result
        if (result = ERROR_SUCCESS) then
        begin
           // Open the redirect to the extension type key
           result:=RegOpenKeyEx(HKEY_CLASSES_ROOT, @lpszTypeKey, 0, KEY_READ, Key);
        end
     finally
        // Close the opened key
        RegCloseKey(hkExt);
     end;
  end;

end;
Comments