I am working on this big C++ Windows application, which runs as Local Service. It tries to get various Windows special paths (using the exact same function as shown below), of those paths it returns:
C:\Program Files
forFOLDERID_ProgramFiles
C:\Program Files (x86)
forFOLDERID_ProgramFilesX86
C:\WINDOWS
forFOLDERID_Windows
But, for FOLDERID_ProgramData
, it returns an empty string. When I tried to use GetLastError()
after SHGetKnownFolderPath()
I get error 203 (ERROR_ENVVAR_NOT_FOUND
):
The system could not find the environment option that was entered.
What I have tried is, when I try to create a small snippet as below, I am able to get C:\ProgramData
for FOLDERID_ProgramData
. It's only when I
try to run my main Windows application that it returns an empty string.
#include <shlobj.h>
#include <iostream>
#include <string>
#include <vector>
#include <iostream>
std::string fun(REFKNOWNFOLDERID val) {
PWSTR dirStr;
if (S_OK == SHGetKnownFolderPath (val, 0, NULL, & dirStr))
{
std::wstring str = std::wstring(dirStr);
std::string ret_str(str.begin(), str.end());
return ret_str;
}
return "failed";
}
int main() {
std::cout << fun(FOLDERID_ProgramData) << std::endl; // outputs C:\ProgramData
std::cout << fun(FOLDERID_ProgramFiles) << std::endl; // outputs C:\Program Files
}
Could it be because I am running the application as Local Service? Do I need to request a specific user's folder by passing the hToken
of Local Service?
If so, how would one go about doing that? I saw Create a user token from SID, expand environment variables in user context, but wanted to make sure if I am on right track.
One thing I noticed is C:\ProgramData
is a hidden folder.