为C#中的新用户创建环境变量 [英] Create environment variables for a new user in C#

查看:220
本文介绍了为C#中的新用户创建环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试在Wix中构建一个产品的安装程序。该产品的一部分需要安装弹性搜索作为服务,并将其作为服务运行。该服务应在单独的用户帐户下运行。

We are trying to build an installer, in Wix, for a product. Part of this product requires the installation of elasticsearch as a service, and getting it running as a service. 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. 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.

为此,我们需要一种方法来创建指定用户下的变量。但是,我们还没有办法使用Wix或C#扩展。

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.

我们最接近的是查询 C#中的ManagementObject ,并发现我们的 ELASTICUSER 的SID。理论上,我们应该可以在HKEY_USERS\< SID> \Environment下的注册表编写另一个环境变量。 >

The closest we have come is to query the ManagementObject in C# and discover the SID for our ELASTICUSER. We should, in theory, 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");
        }

但是,似乎SID在注册表中没有创建,直到用户首先登录。

However, it appears that the SID is not created in the Registry until the user first logs in.

那么,有没有办法使用Wix或者在C#中为没有登录的新创建的用户创建一个环境变量? / p>

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?

推荐答案

是的,从C#可以调用 LoadUserProfile Win32 API功能。这将创建用户的配置文件,如果它不存在,并加载用户的注册表配置单元。

Yes, from C# you can P/Invoke the LoadUserProfile Win32 API function. 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.

这篇关于为C#中的新用户创建环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆