• Welcome to Theos PowerBasic Museum 2017.

AfxGetFileType() function

Started by Jean-Pierre Leroy, August 20, 2012, 05:40:08 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Jean-Pierre Leroy

Hi José,

I found the function AfxGetFileType() very useful; but I need to pass to the function a real filename of the file system.

I would like to know if there is a function that could return the "file type description"  based only on the extension of the file (instead of a full file name).

By example, if I pass ".txt" to the function the result would be "Text Document"

Thanks,
Jean-Pierre

José Roca

One way is to look at the registry. I'm going to add this function to AfxFile.inc.


' ========================================================================================
' Get file content type from file extension looking at the registry.
' ========================================================================================
FUNCTION AfxGetContentTypeFromFileExt (BYVAL bstrExt AS WSTRING) AS WSTRING

   LOCAL hr       AS LONG
   LOCAL hKey     AS DWORD
   LOCAL wszBuff  AS WSTRINGZ * 1024

   IF LEFT$(bstrExt, 1) <> "." THEN bstrExt += "."
   IF RegOpenKeyExW(%HKEY_CLASSES_ROOT, BYCOPY bstrExt, 0, %KEY_QUERY_VALUE, hKey) = %ERROR_SUCCESS THEN
      IF hKey THEN
         ' // First look at the content type
         hr = RegQueryValueExW(hKey, "Content Type", 0, 0, wszBuff, SIZEOF(wszBuff))
         ' // If it fails, look at the default value
         IF hr <> %ERROR_SUCCESS THEN RegQueryValueExW(hKey, "", 0, 0, wszBuff, SIZEOF(wszBuff))
         RegCloseKey hKey
         wszBuff = EXTRACT$(wszBuff, CHR$(0))
      END IF
   END IF

   IF LEN(wszBuff) = 0 THEN wszBuff = "Unknown"
   FUNCTION = wszBuff

END FUNCTION
' ========================================================================================


Jean-Pierre Leroy

Thank you José, It's exactly what I was looking for.

Jean-Pierre