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

问题描述

我正在尝试在我的应用程序中设置一个系统环境变量,但是得到一个 SecurityException 。我测试了我在谷歌发现的一切 - 没有成功。
这是我的代码(注意,我是我的电脑的管理员,并以管理员身份运行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
我也试过以配合我的。

您有其他建议吗?

推荐答案

告诉您如何执行此操作。

The documentation tells you how to do this.

所以,你需要写入注册表设置你已经尝试写信了。然后如上所述广播一个 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:

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

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

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

查看更多