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

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

本文介绍了如何在C#中设置系统环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中设置系统环境变量,但得到的 SecurityException异常。我测试了一切,我发现在谷歌 - 没有成功。这是我的code(注意,我是我的电脑的管理员和运行VS2012作为管理员):

I'm trying to set a system environment variable in my application, but get an 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):

尝试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 我也试图把我的应用程序具有管理员特权时

Attempt 3Also I tried to fit out my app with administrator priviliges.

你有什么其他的建议?

推荐答案

的的告诉你如何做到这一点。

The documentation tells you how to do this.

调用 SetEnvironmentVariable方法对系统环境变量没有影响。要以编程方式添加或修改系统环境变量,把它们添加到 HKEY_LOCAL_MACHINE \系统\ CurrentControlSet \控制\会话管理器\环境的注册表项,然后播放了 WM_SETTINGCHANGE 消息的lParam 设置为字符串环境。这使得应用程序,如外壳,拿起您的更新。

所以,你需要写信给您已经试图写入注册表设置。然后播出 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.

一些例如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");
            }
        }
    }
}

不过,虽然这code不工作,.NET Framework提供的功能,更简单地多执行相同的任务。

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

三个参数的文档 Environment.SetEnvironmentVariable 过载说:

如果目标是EnvironmentVariableTarget.Machine,环境变量存储在HKEY_LOCAL_MACHINE \ SYSTEM \本地计算机的注册表中的ControlSet001 \控制\会话管理器\环境的关键。它也被复制到文件管理器的所有实例。环境变量,然后由从文件浏览器推出任何新的进程继承。

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

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

这篇关于如何在C#中设置系统环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:56