简体   繁体   English

在C#中为新用户创建环境变量

[英]Create environment variables for a new user in C#

We are trying to build an installer, in Wix, for a product. 我们正在尝试使用Wix构建产品的安装程序。 Part of this product requires the installation of elasticsearch as a service, and getting it running as a service. 此产品的一部分要求将Elasticsearch作为服务安装,并使其作为服务运行。 The service should run under a separate user account. 该服务应在单独的用户帐户下运行。

The first step, getting the user account set up, has been successful. 第一步,成功设置用户帐户。 However, in order to allow elasticsearch to run correctly, we need to set up certain Environment variables. 但是,为了使elasticsearch正常运行,我们需要设置某些Environment变量。 In order to reduce the chance of inadvertent user error, we will have to have these variables set under the elasticsearch user, not as machine-wide. 为了减少用户无意中出错的机会,我们将必须在Elasticsearch用户下而不是在机器范围内设置这些变量。

To this end, we need a way to create the variables under the specified user only. 为此,我们需要一种仅在指定用户下创建变量的方法。 However, we have not yet been able to work out a way to do this, either using Wix or a C# extension. 但是,我们仍无法找到使用Wix或C#扩展名的方法。

The closest we have come is to query the ManagementObject in C# and discover the SID for our ELASTICUSER . 我们最接近的是在C#中查询ManagementObject并发现ELASTICUSER的SID。 We should, in theory, be able to write another environment variable to the Registry, under "HKEY_USERS\\<SID>\\Environment" , as shown. 从理论上讲,我们应该能够在注册表的"HKEY_USERS\\<SID>\\Environment"下向注册表写入另一个环境变量,如图所示。

        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 appears that the SID is not created in the Registry until the user first logs in. 但是,似乎在用户首次登录之前,不会在注册表中创建SID。

So, is there any way to use either Wix, or in C# to create an environment variable for a newly created user that has never logged in? 因此,有没有办法使用Wix或C#为从未登录的新创建用户创建环境变量?

Yes, from C# you can P/Invoke the LoadUserProfile Win32 API function. 是的,从C#中可以P /调用LoadUserProfile Win32 API函数。 This will create the user's profile if it does not already exist, and load the user's registry hive. 如果它不存在,将创建用户的配置文件,并加载用户的注册表配置单元。

I would not recommend this approach for an account that will be used for interactive logons, but it should be safe enough for a service account. 我不建议将这种方法用于将用于交互式登录的帐户,但是对于服务帐户而言,它应该足够安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM