简体   繁体   English

如何在C#中设置系统环境变量?

[英]How to set system environment variable in C#?

I'm trying to set a system environment variable in my application, but get an SecurityException .我试图在我的应用程序中设置一个系统环境变量,但得到一个SecurityException I tested everything I found in google - without success.我测试了我在谷歌中找到的所有内容 - 没有成功。 Here is my code (note, that I'm administrator of my pc and run VS2012 as admin):这是我的代码(注意,我是我的电脑的管理员并以管理员身份运行 VS2012):

Attempt 1尝试 1

new EnvironmentPermission(EnvironmentPermissionAccess.Write, "TEST1").Demand();
Environment.SetEnvironmentVariable("TEST1", "MyTest", EnvironmentVariableTarget.Machine);

Attempt 2尝试 2

new EnvironmentPermission(EnvironmentPermissionAccess.Write, "TEST1").Demand();

using (var envKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
{

  Contract.Assert(envKey != null, @"HKLM\System\CurrentControlSet\Control\Session Manager\Environment is missing!");
  envKey.SetValue("TEST1", "TestValue");
}

Attempt 3 Also I tried to fit out my app with administrator priviliges .尝试 3此外,我还尝试使用管理员权限来安装我的应用程序

Do you have any other suggestions?您还有其他建议吗?

The documentation tells you how to do this.文档告诉您如何执行此操作。

Calling SetEnvironmentVariable has no effect on the system environment variables.调用SetEnvironmentVariable对系统环境变量没有影响。 To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment" .要以编程方式添加或修改系统环境变量,请将它们添加到HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment注册表项,然后广播WM_SETTINGCHANGE消息,其中lParam设置为字符串"Environment" This allows applications, such as the shell, to pick up your updates.这允许应用程序(例如 shell)获取您的更新。

So, you need to write to the registry setting that you are already attempting to write to.因此,您需要写入您已经尝试写入的注册表设置。 And then broadcast a WM_SETTINGCHANGE message as detailed above.然后广播WM_SETTINGCHANGE消息,如上所述。 You will need to be running with elevated rights in order for this to succeed.您需要以更高的权限运行才能成功。

Some example code:一些示例代码:

using Microsoft.Win32;
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        const int HWND_BROADCAST = 0xffff;
        const uint WM_SETTINGCHANGE = 0x001a;

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, 
            UIntPtr wParam, string lParam);

        static void Main(string[] args)
        {
            using (var envKey = Registry.LocalMachine.OpenSubKey(
                @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
                true))
            {
                Contract.Assert(envKey != null, @"registry key is missing!");
                envKey.SetValue("TEST1", "TestValue");
                SendNotifyMessage((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE,
                    (UIntPtr)0, "Environment");
            }
        }
    }
}

However, whilst this code does work, the .net framework provides functionality to perform the same task much more simply.然而,虽然此代码确实有效,但 .net 框架提供了更简单地执行相同任务的功能。

Environment.SetEnvironmentVariable("TEST1", "TestValue", 
    EnvironmentVariableTarget.Machine);

The documentation for the three argument Environment.SetEnvironmentVariable overload says:三个参数Environment.SetEnvironmentVariable重载的文档说:

If target is EnvironmentVariableTarget.Machine, the environment variable is stored in the HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment key of the local computer's registry.如果目标是 EnvironmentVariableTarget.Machine,则环境变量存储在本地计算机注册表的 HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment 键中。 It is also copied to all instances of File Explorer.它还会复制到文件资源管理器的所有实例。 The environment variable is then inherited by any new processes that are launched from File Explorer.然后,从文件资源管理器启动的任何新进程都会继承环境变量。

If target is User or Machine, other applications are notified of the set operation by a Windows WM_SETTINGCHANGE message.如果目标是用户或机器,则通过 Windows WM_SETTINGCHANGE 消息通知其他应用程序设置操作。

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

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