I am trying to add a folder to my "Path" environment variable by doing the following:
string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
path = path @";C:\my\new\path";
Environment.SetEnvironmentVariable("Path", path, EnvironmentVariableTarget.Machine);
This adds my new folder to the Path variable successfully, however any existing Path folders that had been represented by an environment variable are now expanded out.
For example, I have an environment variable JAVA_HOME that points to C:\Program Files\Java\jdk-17, and in the Path variable I originally had an entry that read %JAVA_HOME%\bin. However, after doing the above update, now that Path entry reads C:\Program Files\Java\jdk-17\bin.
When I examine the string returned by Environment.GetEnvironmentVariable(), I see that it returns the paths already expanded out rather than the %JAVA_HOME% placeholder. How do I update the Path variable without saving the existing paths in their expanded forms and instead maintain their variable names?
CodePudding user response:
It seems that Environment.GetEnvironmentVariable
always expands environment variables which are embedded in other environment variables, and there's no option to change this behaviour.
You could instead try reading the environment variable from the registry, e.g.
using System;
using Microsoft.Win32;
class Program
{
static void Main(string[] args)
{
var keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
var key = Registry.LocalMachine.OpenSubKey(keyName);
var pathFromRegistry = key.GetValue("Path", "not found", RegistryValueOptions.DoNotExpandEnvironmentNames);
Console.WriteLine(pathFromRegistry);
}
}
I wrote this example in a .net core 3.1 console application, which needed the Microsoft.Win32.Registry
nuget package before the Microsoft.Win32
namespace could be used.
There's a GitHub issue with discussion about why Environment.GetEnvironmentVariable
doesn't provide this same functionality.