Tamás Szelei
Tamás Szelei

Reputation: 23921

How to edit the registry keys of a specific user programatically?

I want to change a few settings of a Windows user that I created in my application. If I understand correctly, his "HKEY_CURRENT_USER" values will be under HKEY_USERS/<sid>/.... Is this correct? How can I get the sid of the user, if I know the user name and the domain?

Edit: How can I correctly edit the HKCU keys of that user, if I have the sid already?

Upvotes: 7

Views: 7277

Answers (3)

deutschZuid
deutschZuid

Reputation: 1058

I have a program that does exactly that. Here is the relevant part of the code:

NTAccount ntuser = new NTAccount(strUser);
SecurityIdentifier sID = (SecurityIdentifier) ntuser.Translate(typeof(SecurityIdentifier));
strSID = sID.ToString();

You will need to import two namespaces:

using System.DirectoryServices;
using System.Security.Principal;

Hope this helps.

Then use Registry.Users.SetValue with SID string\path to set the registry value.

This might not work as intended if you are editing a logged-off profile, especially a roaming profile.

Upvotes: 3

Raj Ranjhan
Raj Ranjhan

Reputation: 3917

You can use Query by example and search using PrincipalSearcher for appropriate UserPrincipal

// Since you know the domain and user
PrincipalContext context = new PrincipalContext(ContextType.Domain);

// Create the principal user object from the context
UserPrincipal usr = new UserPrincipal(context);
usr .GivenName = "Jim";
usr .Surname = "Daly";

// Create a PrincipalSearcher object.
PrincipalSearcher ps = new PrincipalSearcher(usr);
PrincipalSearchResult<Principal> results = ps.FindAll();
foreach (UserPrincipal user in results) {
    if(user.DisplayName == userName) {
        var usersSid = user.Sid.ToString();
    }
}

Upvotes: 0

Mike Zboray
Mike Zboray

Reputation: 40818

There are two steps to this. First you must get the users sid. Second you must load the users registry hive. Other users hives are not loaded by default so you must load it explicitly.

The answer in Daniel White's comment is the best way to get the sid.

To load the user's registry hive, use the LoadUserProfile windows API via pinvoke. There is a complementary UnloadUserProfile to unload the hive when you are done with it.

Upvotes: 2

Related Questions