且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-24 01:54:57

文档告诉您如何执行此操作。

The documentation tells you how to do this.


调用 SetEnvironmentVariable 对系统环境变量没有影响。以编程方式添加或修改系统环境变量,将它们添加到 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment 注册表项,然后广播 WM_SETTINGCHANGE 消息与 lParam 设置为字符串环境。这允许诸如shell的应用程序来接收更新。

Calling SetEnvironmentVariable has no effect on the system environment variables. 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". This allows applications, such as the shell, to pick up your updates.

所以,你需要写入注册表设置你已经尝试写信了。然后如上所述广播一个 WM_SETTINGCHANGE 消息。您将需要运行提升版权才能使其成功。

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. You will need to be running with elevated rights in order for this to succeed.

一些示例代码:

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");
            }
        }
    }
}

虽然这个代码是有效的,但是.NET框架提供了更简单地执行相同任务的功能。

However, whilst this code does work, the .net framework provides functionality to perform the same task much more simply.

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

The documentation for the three argument Environment.SetEnvironmentVariable overload says:


如果target是EnvironmentVariableTarget.Machine,则环境变量存储在本地计算机注册表的HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment键中。它也被复制到文件资源管理器的所有实例。然后环境变量继承自从文件资源管理器启动的任何新进程。

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. 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.

如果目标是用户或计算机,其他应用程序将通过Windows通知设置操作WM_SETTINGCHANGE消息。

If target is User or Machine, other applications are notified of the set operation by a Windows WM_SETTINGCHANGE message.