How to programmatically edit registry keys for a specific user?

I want to change some settings of the Windows user created in the application. If I understand correctly, its values ​​" HKEY_CURRENT_USER " will be under HKEY_USERS/<sid>/... It's right? How can I get the user sid if I know the username and domain?

Edit: how can I correctly edit the HKCU keys of this user if I already have a sid?

+7
source share
3 answers

I have a program that does just that. Here is the relevant piece of 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 may not work properly if you are editing a profile with a profile disabled, especially a roaming profile.

+3
source

There are two steps to this. You should get sid users first. Secondly, you must download the user registry hive. Other user hives do not load by default, so you must explicitly download it.

The answer in a comment by Daniel White is the best way to get seed.

To load the user registry hive, use the LoadUserProfile windows API through pinvoke. There is an optional UnloadUserProfile for unloading the hive when you are done with it.

+2
source

You can use the Query by example and search using PrincipalSearcher for the corresponding 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(); } } 
0
source

All Articles