sailer
sailer

Reputation: 459

How can we set/get other users Environment variable in c#?

User Environment variables are separate for each user account on machine.

Consider the following, I'm logged in with userA which is non admin user account, now I want to get/set other user's (say userB) environment variable by using C# application running in userA's context.

Is this possible to do? And if so, how could I do this?

Upvotes: 0

Views: 4295

Answers (1)

Bali C
Bali C

Reputation: 31231

The environment variables are stored in the registry, so to change them for another user you would have to import their registry hive.

The key for user vars is

HKEY_CURRENT_USER\Environment

and the key for system vars is

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

So if you import the current user hive you can change it for other users, or for machine vars change the HKLM key from any admin account.

This is messy though and I wouldn't advise you do it.

Or you can use some P/Invoke to use Impersonation.

Upvotes: 1

Related Questions