Edit registry key of other user
How to change or edit regist开发者_如何学Gory values of other user than the current user? I know the credentials of that other user.
You can impersonate the user and then change the registry for that current context. Here are a couple of resources on C# and Impersonation:
- Windows Impersonation using C#
- Windows Impersonation from C#
What you want to do is something like this (pseudo):
using(var impersonation = new Impersonate(username,password))
{
ChangeRegistry(keys, values);
}
And when the impersonation is disposed, you are back using the running user again. Here is an example implementation of an Impersonate class that implements IDisposable to act like the pseudo-exampel shown above and here is another example.
Here is an example on how you change registry values:
var registry = Registry.CurrentUser;
var key =
registry.OpenSubKey(
@"HKEY_CURRENT_USER\Some\Path\That\You\Want\ToChange", true);
key.SetValue(null, "");
Registry.CurrentUser.Flush();
Update
So what you need to do in order to access HKCU
is that you also have to load the user profile. This is done by invoking another Win32 Method that is called LoadUserProfile
. There's a complete example here that you can use, but I'm going to include the important bits here.
First you need to include the Win32 methods like this:
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool LoadUserProfile(IntPtr hToken,
ref ProfileInfo lpProfileInfo);
[DllImport("userenv.dll", CallingConvention = CallingConvention.Winapi,
SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool UnloadUserProfile(IntPtr hToken,
IntPtr lpProfileInfo);
Inside your impersonation using-block you need to do the following:
ProfileInfo profileInfo = new ProfileInfo();
profileInfo.dwSize = Marshal.SizeOf(profileInfo);
profileInfo.lpUserName = userName;
profileInfo.dwFlags = 1;
Boolean loadSuccess = LoadUserProfile(tokenDuplicate, ref profileInfo);
And after this you should be able to access the HKCU
. When you're done, you need to unload the profile using UnloadUserProfile(tokenDuplicate, profileInfo.hProfile);
.
You have two options. You can impersonate that user if you have their credentials as Filip Ekberg better demonstrates; or
HKCU is just a symbolic link for one of the keys under HKEY_USERS
. If you know the SID of that user, then you can find it in there. You can get the SID as so:
var account = new NTAccount("userName");
var identifier = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
var sid = identifier.Value;
The better option is to impersonate. The second option might work better when you don't know that user's credentials. The disadvantage is you will need administrative rights to write in someone else's account.
精彩评论