【发布时间】:2015-08-07 11:29:39
【问题描述】:
我需要添加一个 Windows 环境变量,就像 Windows 中现有的一样。我的意思是:
当您在 cmd.exe 中运行以下行时:
echo %appdata% //outputs something like C:/Users/blablabla
// It's saved in windows by default !
我正在制作一个简单的 Winform 应用程序,它可以使用 C# 轻松创建 windows 环境变量
我试过了:
System.Environment.SetEnvironmentVariable("test", "testvalue", EnvironmentVariableTarget.Machine);
我试过this,但都没有:
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);
using (var envKey = Registry.LocalMachine.OpenSubKey(
@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
true))
{
Contract.Assert(envKey != null, @"registry key is missing!");
envKey.SetValue("artyom", "TestValue");
SendNotifyMessage((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE,
(UIntPtr)0, "Environment");
}
// it is assumed after this , the list should display this value, but nothing happens ! No exceptions, nothing
然后阅读:
msdn docs - Other link here ...
EnvironmentVariableTarget.Machine 似乎根本没有帮助。
如果此过程成功,我将能够在 cmd.exe 中执行此操作
echo %test% // and outputs "testvalue"
请记住,当用户单击按钮并且我在 WinForms 中工作时,我正在测试所有这些代码 是否可以使用 C# 执行此操作?任何帮助表示赞赏,谢谢
【问题讨论】:
-
其他选项的代码在哪里,包括广播消息?
-
更新了@RowlandShaw
-
您在程序中设置的环境变量在程序执行之前已经启动的命令提示符下是不可见的。所以...关闭命令提示符,运行您的软件,打开它并查看它是否存在。对于“机器”环境变量,请以管理员身份运行您的程序。
-
非常重要的评论@JeroenLandheer!解决了我的部分问题!
标签: c# .net windows winforms environment