Sunday, July 12, 2009

C++ LoadUserProfile() call fails in Vista only. Why?

My application works in WinXP, Win2K but not in Vista. It uses the Windows API call LoadUserProfile() so it should work.





Any ideas on how to make this work in Vista?





Here is my code:





PROFILEINFO pi;


ZeroMemory(%26amp;pi,sizeof(pi));


pi.dwSize = sizeof(PROFILEINFO);





HANDLE hToken = NULL;


BOOL fStatus = OpenProcessToken(GetCurrentProcess(),


TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE,


%26amp;hToken);








if(!fStatus || hToken == NULL)


{


// display error message to user


return false;


}





char pszUname[UNLEN + 1];


ZeroMemory(pszUname,sizeof(pszUname));


DWORD dwSize = UNLEN;


fStatus = GetUserName(pszUname,%26amp;dwSize);





if(!fStatus)


{


// display error message to user


CloseHandle(hToken);


return false;


}





pi.lpUserName = pszUname;





// THIS IS THE LINE THAT IS FAILING ONLY


// WHEN RUN IN VISTA!


fStatus = LoadUserProfile(hToken,%26amp;pi);


// ----------------------------------





CloseHandle(hToken);





if(!fStatus)


{


// display error message to user


return false;


}





Many thanks!

C++ LoadUserProfile() call fails in Vista only. Why?
Why don't you actually check what the fStatus value is? Do as your comment say, and do a GetLastError() on the fStatus value. I don't have access to a vista machine so I can't see what happen but that should give you some more information to figure out what is going on. If you still can't figure it out. Post an update, maybe someone will be able to help.





DWORD errorCode = GetLastError();


LPVOID lpMsgBuf;


DWORD nbChar = FormatMessage(


FORMAT_MESSAGE_ALLOCATE_BUFFER


|FORMAT_MESSAGE_FROM_SYSTEM|


FORMAT_MESSAGE_IGNORE_INSERTS,


NULL, errorCode, 0, (LPTSTR) %26amp;lpMsgBuf, 0, NULL);


OutputDebugString(


(LPCTSTR)lpMsgBuf);


LocalFree( lpMsgBuf );





Good luck.








UPDATE: extract from MSDN: (You may want to look into the registry note and the privilege thingy.)





Note that it is your responsibility to load the user's registry hive into the HKEY_USERS registry key with the LoadUserProfile function before calling CreateProcessAsUser. This is because CreateProcessAsUser does not load the specified user's profile into HKEY_USERS. This means that access to information in the HKEY_CURRENT_USER registry key may not produce results consistent with a normal interactive logon.





The calling process must have the SE_RESTORE_NAME and SE_BACKUP_NAME privileges. For more information, see Running with Special Privileges.





Starting with Windows XP SP2 and Windows Server 2003, the caller must be an administrator or the LocalSystem account.

wildflower

No comments:

Post a Comment