最近项目需求需要获取用户的图片路径作为默认的图片路径,用windows的API获取,发现在控制台下得到如下结果:
但是如果以service运行的时候,得到的却是这样的路径:
经过诸多波折才知道,service状态下和普通用户运行程序的令牌不一样,如果是系统用户下,需要切换到当前用户的token,才能得到当前用户的文件目录。
具体代码如下:
BOOL CurrentUserIsLocalSystem()
{
BOOL bIsLocalSystem = FALSE;
PSID psidLocalSystem;
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
BOOL fSuccess = ::AllocateAndInitializeSid(&ntAuthority, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &psidLocalSystem);
if (fSuccess)
{
fSuccess = ::CheckTokenMembership(0, psidLocalSystem, &bIsLocalSystem);
::FreeSid(psidLocalSystem);
}
return bIsLocalSystem;
}
//获取图片文件夹目录
BOOL GetAppDataPathA(char *pszDefaultDir) {
char szDocument[MAX_PATH] = { 0 };
LPITEMIDLIST pidl = NULL;
SHGetSpecialFolderLocation(NULL, CSIDL_MYPICTURES, &pidl);
if (pidl && SHGetPathFromIDListA(pidl, szDocument))
{
return (0 != GetShortPathNameA(szDocument, pszDefaultDir, _MAX_PATH));
}
return FALSE;
}
//获取当前用户的图片文件夹目录
std::string getCurrentUserPicturePath() {
std::string retValue = "";
HANDLE hTokenUser = NULL;
DWORD ConsoleSessionId = 0;
BOOL bImpersonateLoggedOnUser = FALSE;
if (CurrentUserIsLocalSystem())
{
// 得到当前激活用户的会话ID
ConsoleSessionId = WTSGetActiveConsoleSessionId();
// 得到当前登录用户的令牌
if (WTSQueryUserToken(ConsoleSessionId, &hTokenUser))
{
// 模仿成当前登录用户
bImpersonateLoggedOnUser = ImpersonateLoggedOnUser(hTokenUser);
}
}
char szPicturePath[MAX_PATH] = { 0 };
if (GetAppDataPathA(szPicturePath))
{
retValue = szPicturePath;
}
// 终止模拟,返回
if (bImpersonateLoggedOnUser)
{
RevertToSelf();
}
std::cout << "default Path: " << retValue << "\n";
LOGD_(smart::LOG_ALG_INFO) << "default Path: " << retValue << "\n";
return retValue;
}