How to Set System Environment Variable in C#

How to set system environment variable in C#?

The documentation tells you how to do this.

Calling SetEnvironmentVariable has no effect on the system environment variables. To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.

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.

Some example 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");
}
}
}
}

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:

If target is EnvironmentVariableTarget.Machine, the environment variable is stored in the HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment key of the local computer's registry. It is also copied to all instances of File Explorer. The environment variable is then inherited by any new processes that are launched from File Explorer.

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

How to set Environment variables permanently in C#

While the program is running, after using Set, the value is returned
using Get without any issue. The problem is the environment variable
isn't permanent (being set on the system).

Thats because the overload of SetEnvironmentVariable that you're using stores in the process variables. From the docs:

Calling this method is equivalent to calling the
SetEnvironmentVariable(String, String, EnvironmentVariableTarget)
overload with a value of EnvironmentVariableTarget.Process for the
target argument.

You need to use the overload specifying EnvironmentVariableTarget.Machine instead:

public static void Set(string name, string value) 
{
Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.Machine);
}

How to set environment variable Path using C#

You are associating the environment variable with your program, but instead you want to associate it with your local machine in order to make it available to every program. Look at the overload that takes an EnvironmentVariableTarget.

var name = "PATH";
var scope = EnvironmentVariableTarget.Machine; // or User
var oldValue = Environment.GetEnvironmentVariable(name, scope);
var newValue = oldValue + @";C:\Program Files\MySQL\MySQL Server 5.1\bin\\";
Environment.SetEnvironmentVariable(name, newValue, scope);

How do I get and set Environment variables in C#?

Use the System.Environment class.

The methods

var value = System.Environment.GetEnvironmentVariable(variable [, Target])

and

System.Environment.SetEnvironmentVariable(variable, value [, Target])

will do the job for you.

The optional parameter Target is an enum of type EnvironmentVariableTarget and it can be one of: Machine, Process, or User. If you omit it, the default target is the current process.

How to use system\environment variables in .NET string?

Use System.Environment.ExpandEnvironmentVariables like so:

String concretePath = Environment.ExpandEnvironmentVariables(@"%TEMP%\myapplication\data");

How to Create,set,Read and Delete environment variable using C# and VB.Net programming languages

You can use Environment.SetEnvironmentVariable
to create, modify or delete environment variable and
Environment.GetEnvironmentVariable
for retrieve it.

Reference: https://learn.microsoft.com/en-us/dotnet/api/system.environment.setenvironmentvariable?view=netframework-4.7.2
To delete you set it to null.

Set an Environment Variable Programatically in the Machine Scope and send SettingsChange Message

Setting machine-level environment variable is a bit tricky. The problem is that does not immediate effect on the processes as they already running within their own environment. See more there: https://serverfault.com/questions/8855/how-do-you-add-a-windows-environment-variable-without-rebooting I'm not sure that Environment.SetEnvironmentVariable will do it for you.

C# Setting Environment Vairables

When storing environmental variables like this they are only stored as long as the process is running. If you close your program the variables are gone.

    static void Main(string[] args)
{
string MyEnv = string.Empty;

MyEnv = Environment.GetEnvironmentVariable("MyEnv");
Console.WriteLine("MyEnv=" + MyEnv);

MyEnv = "True";
Environment.SetEnvironmentVariable("MyEnv", MyEnv);
MyEnv = Environment.GetEnvironmentVariable("MyEnv");
Console.WriteLine("MyEnv=" + MyEnv);

MyEnv = "False";
Environment.SetEnvironmentVariable("MyEnv", MyEnv);
MyEnv = Environment.GetEnvironmentVariable("MyEnv");
Console.WriteLine("MyEnv=" + MyEnv);

Console.ReadLine();
}

Output:

MyEnv=
MyEnv=True
MyEnv=False


Related Topics



Leave a reply



Submit