I have a Windows service running under a LocalSystem account and I am trying to access some user-specific environment variables. When I call ExpandEnvironmentStrings("%AppData%"), I get "C:\windows\system32\config\systemprofile\AppData\Roaming".
I figured impersonation and loading the user profile should solve this, so I called:
And still, ExpandEnvironmentStrings("%AppData%") returns the the system folder instead of something like "C:\Users\Username\AppData\Roaming".
So then I searched around some more and came across SHGetFolderPath(CSIDL_LOCAL_APPDATA), which worked like a charm post-impersonation.
My question is not what I should do (ie. SHGetFolderPath), but more about how environment variables work in services. I'm thinking my issue is either:
My LoadUserProfile() code is still missing something, even though everything returns success. My ignorant side wants to convince me that in theory, loading a user profile should make ExpandEnvironmentStrings() return the loaded user's values.
Based on some readings, it seems environment variables in services are read only once (http://support.microsoft.com/kb/887693) at system startup, so my service is ONLY aware of system environment variables.
I'm leaning towards 2. but I just need someone to confirm this, so I don't assume something that's potentially wrong.
User environment variables, as the name suggests, are environment variables that are specific to each user account. This means that the value of a variable when logged in as one user can be different than the value of the same variable when logged in as a different user on the same computer.
Impersonation allows users with the admin or the impersonator role to temporarily become another authenticated user for testing purposes. Impersonation does not require knowing another user's password. When impersonating another user, the admin user can see and do exactly what the impersonated user can see and do.
User impersonation allows you to temporarily sign in as a different user in your network. Users with full impersonation permissions can impersonate all other users in their network and take any action, regardless of the impersonating user's own permission level. Impersonators appear as themselves in the change history.
System and user environment variables (configured for each user, set for everyone). All users can access system environment variables worldwide. User environment variables only apply to the user that is logged in at the moment.
The docs for Environment variables indicate that #2 is correct. Quoting, emphasis added:
Every process has an environment block that contains a set of environment variables and their values.
MSDN points to ExpandEnvironmentStringForUser()
to approach your original problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With