Search code examples
c#registry

How to change registry entries of different users?


I am working on a C# desktop application and i require so store some settings individually for each user in the HKCU section of the registry for each user. the requirements are such that these settings cannot be stored in a file or the database and registry is the best solution if possible.. Is it not possible to use impersonate method as we might not know passwords of all the users. however we will have the administrator access when running the exe.

is there a way that with administrator access we can access HKCU section for each user and populate the settings there


Solution

  • According to your scenario the first option was to impersonate the user, but as you are not willing to adopt it, now we have another option, obtain the user's SID, and then write the data under the KEY_USERS registry because this path contains all users in the machine.

    Following is the utility function to write a value to specific user's registry key, obviously you need to know his/her username.

    public static bool AddUserData(string userName, string key, string value)
    {
       try
       {
            //Gets the SID of the desired user
            NTAccount f = new NTAccount(userName);
            SecurityIdentifier s = (SecurityIdentifier)f.Translate(typeof(SecurityIdentifier));
            string sid = s.ToString();
    
            //Define the path to the subkey
            string path = @"SOFTWARE\Console\DefaultConfig";
    
            //try to open the path
            var reg = Registry.Users.OpenSubKey(string.Format("{0}\\{1}", sid, path), true);
            if (reg == null)
            {
                //if not exists create that path for that user
                reg = Registry.Users.CreateSubKey(string.Format("{0}\\{1}", sid, path));
            }
    
            //set value against key
            reg.SetValue(key, value);
            return true;
        }
       catch
       {
           return false;
       }
    }
    

    feel free to check documentation of the Registry class so that you will learn better to read the value back, this is just starting direction for you, Also I have not tested the code but I am pretty sure this will help you a lot. The admin access for the program is must for this code to work, otherwise you are left with impersonation.