Creating environment variables for a new user in C #

We are trying to create an installer in Wix for the product. Part of this product requires the installation of elasticsearch as a service and to ensure its operation as a service. The service must run under a separate user account.

The first step, setting up the user account, was successful. However, to allow elasticsearch to work correctly, we need to configure certain environment variables. To reduce the likelihood of an unintentional user error, we will need to set these variables under the elasticsearch user, and not throughout the machine.

To this end, we need a way to create variables only for the specified user. However, we have not yet been able to develop a way to do this using Wix or the C # extension.

Closest we came to request ManagementObjectin C # and to find SID for ours ELASTICUSER. Theoretically, we should be able to write another environment variable to the registry under "HKEY_USERS\<SID>\Environment", as shown.

        var query = new SelectQuery("Win32_UserAccount");
        var manObjSearch = new ManagementObjectSearcher(query);
        var stringToWrite = string.Empty;
        foreach (var envVar in manObjSearch.Get())
        {
            if (envVar["Name"].ToString().ToUpperInvariant() == "ELASTICUSER")
            {
                elasticUserSid = envVar["SID"].ToString();
            }
        }

        using (var key = Registry.Users.OpenSubKey(elasticUserSid + "\\Environment"))
        {
            if (key == null)
            {
                return;
            }

            key.SetValue("OurVariable", "Value");
        }

However, it seems that the SID is not created in the registry until the user logs in.

So, is there a way to use either Wix or C # to create an environment variable for a newly created user who has never logged in?

+4
source share
1 answer

Yes, with C # you can P / call the LoadUserProfileWin32 API function . This will create a user profile if it does not already exist, and load the user registry hive.

, , .

+2

Source: https://habr.com/ru/post/1672384/


All Articles