如何在C#中设置系统环境变量?
我正在尝试在我的应用程序中设置系统环境变量,但获得SecurityException
。 我测试了我在谷歌找到的所有内容 – 没有成功。 这是我的代码(请注意,我是我的电脑的管理员并以管理员身份运行VS2012):
尝试1
new EnvironmentPermission(EnvironmentPermissionAccess.Write, "TEST1").Demand(); Environment.SetEnvironmentVariable("TEST1", "MyTest", EnvironmentVariableTarget.Machine);
尝试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"); }
尝试3此外,我试图用管理员权限assembly我的应用程序 。
你有什么其他的建议?
文档告诉您如何执行此操作。
调用
SetEnvironmentVariable
对系统环境变量没有影响。 若要以编程方式添加或修改系统环境变量,将它们添加到HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment
注册表项,然后广播WM_SETTINGCHANGE
消息,并将lParam
设置为字符串"Environment"
。 这允许应用程序(如shell)获取更新。
因此,您需要写入您已尝试写入的注册表设置。 然后如上所述广播WM_SETTINGCHANGE
消息。 您需要以提升的权限运行才能成功。
一些示例代码:
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框架提供了更简单地执行相同任务的function。
Environment.SetEnvironmentVariable("TEST1", "TestValue", EnvironmentVariableTarget.Machine);
三个参数Environment.SetEnvironmentVariable
重载的文档说:
如果target是EnvironmentVariableTarget.Machine,则环境变量存储在本地计算机注册表的HKEY_LOCAL_MACHINE \ SYSTEM \ ControlSet001 \ Control \ Session Manager \ Environment项中。 它也会复制到文件资源管理器的所有实例中。 然后,环境变量将由从文件资源管理器启动的任何新进程inheritance。
如果target是User或Machine,则通过Windows WM_SETTINGCHANGE消息向其他应用程序通知设置操作。