I need to add a Windows Environment Variable like the existing in windows. I mean :
When you run the following line in the cmd.exe :
echo %appdata% //outputs something like C:/Users/blablabla
// It's saved in windows by default !
I'm making a simple Winform application that makes the creation of the windows environment variables easy with C#
I have tried :
System.Environment.SetEnvironmentVariable("test", "testvalue", EnvironmentVariableTarget.Machine);
I tried with this but neither :
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
And read :
msdn docs - Other link here ...
The EnvironmentVariableTarget.Machine doesn't seems to help at all.
If this process is successful, i would be capable of do this in cmd.exe
echo %test% // and outputs "testvalue"
Keep in mind i'm testing all this code when the user click a button and i'm working in WinForms it's possible to do this with C# or not ? Any help is appreciated, thanks