tags:

views:

49

answers:

2

Hi, I am trying to display file type of given filename (based on extension) using AssocQueryKey() API function. The problem is thar return wrong HKEY value sometimes. For example the following function works correctly on win 7 ultimate x64, but fails for some extensions like ".mp3" on my win xp x86 machine (other extensions works though). Even when "succeeded" and returns S_OK, GetLastError() is 1008 ALWAYS after AssocQueryKey() call:

// Return STL string representation of file type from windows registry
stlstring GetFileTypeFromRegistry(const stlstring& m_filename)
{
 CRegKey reg;
 HKEY key = {0};
 stlstring s;
 //Get file extension
 LPCTSTR fExt = PathFindExtension(m_filename.c_str());
 if(AssocQueryKey(NULL, ASSOCKEY_CLASS, fExt, TEXT(""),  &key) != S_OK)
  DisplayError(_T("AssocQueryKey != S_OK"), GetLastError());
 else
  DisplayError(_T("AssocQueryKey == S_OK"), GetLastError());

 if(reg.Open ( key, NULL, KEY_QUERY_VALUE) != ERROR_SUCCESS){
  reg.Close();
  DisplayError((LPTSTR)fExt);
  return s;
 }
 //DWORD out = 0;
 /*WCHAR *h = new WCHAR[1024];
 ZeroMemory(h, sizeof(h));
 AssocQueryStringByKey(0, ASSOCSTR_EXECUTABLE, HKEY_CLASSES_ROOT, NULL, h, &out);
 //MessageBox(0,_T("gbtbb"),h,MB_OK);
 delete[] h;*/
 ULONG m_sz = 256;
 //if( reg.QueryStringValue(NULL, NULL, &m_sz) == ERROR_SUCCESS){

  TCHAR *m_regstring = new TCHAR[m_sz + 1];
   if(reg.QueryStringValue(NULL, m_regstring, &m_sz) == ERROR_SUCCESS){
    //DisplayError(_T(""));
    s += m_regstring;
   /*delete[] m_regstring; m_regstring = NULL;
   reg.Close();
    return s;*/
   } else {
    DisplayError(_T("CRegKey::QueryStringValue()"), GetLastError());
   }
   s += m_regstring;
   delete[] m_regstring; m_regstring = NULL;
   reg.Close();
   return s;
 /*}
 reg.Close();
 return s;*/
}

Any ideas on this ?? This function is from a DLL which is loaded by windows explorer, implementing IQueryInfo::GetInfoTip() if that matters.

+2  A: 

You shouldn't use GetLastError for functions that return the error code directly. The MSDN page for AssocQueryKey says "Returns S_OK if successful, or a COM error value otherwise.", which means you already get the error code in the return value.

If you just want to get the file type information, there's a much simpler solution: SHGetFileInfo. It's really simple to use, like this:

SHFILEINFO shfi;
SHGetFileInfo(filename, 0, &shfi, sizeof(shfi), SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES);
// shfi.szTypeName now contains the file type string of the given filename
casablanca
A: 

SHGetFileInfo() did the trick, thank you.

modoran