服务或应用程序作为“本地系统”运行以获取特殊文件夹
这个例子我们得到CSIDL_DESKTOPDIRECTORY,在 xp 上运行良好,win7(32,64)
DWORD ServiceGetDesktopDirectory(LPWSTR lpUserName, LPWSTR lpPassword,
LPWSTR lpDomain, LPWSTR lpBuffer)
{
HANDLE hToken;
BOOL bRet;
bRet = LogonUserW(lpUserName,
lpDomain,
lpPassword,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
&hToken);
if (!bRet) {
error("LogonUser failed, gle = %lu", GetLastError());
return FILE_ERR_INVALID_USERNAME_OR_PASSWORD;
}
NET_API_STATUS ntStatus;
USER_INFO_4 *pUserInfo;
ntStatus = NetUserGetInfo((LPCWSTR)lpDomain,
(LPCWSTR)lpUserName,
4,
(BYTE**)&pUserInfo);
if (ntStatus != NERR_Success) {
error("NetUserGetInfo failed, ntStatus 0X%x", ntStatus);
CloseHandle(hToken);
return FILE_ERR_SYSTEM_ERROR;
}
PROFILEINFOW profile;
memset(&profile, 0, sizeof(PROFILEINFOW));
profile.dwSize = sizeof(PROFILEINFOW);
profile.lpUserName = lpUserName;
profile.lpProfilePath = pUserInfo->usri4_profile;
bRet = LoadUserProfileW(hToken, &profile);
if (!bRet) {
error("LoadUserProfile failed, gle = %lu", GetLastError());
CloseHandle(hToken);
NetApiBufferFree(pUserInfo);
return FILE_ERR_SYSTEM_ERROR;
}
HRESULT hr;
hr = SHGetFolderPathW(NULL,
CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE,
hToken,
0,
lpBuffer);
if (FAILED(hr)) {
error("SHGetFolderPath failed, hr 0X%x", hr);
NetApiBufferFree(pUserInfo);
UnloadUserProfile(hToken, profile.hProfile);
CloseHandle(hToken);
return FILE_ERR_SYSTEM_ERROR;
}
NetApiBufferFree(pUserInfo);
UnloadUserProfile(hToken, profile.hProfile);
CloseHandle(hToken);
return FILE_ERR_OK;
}