I want to extend the current PATH variable with a C# program. Here I have several problems:
Using GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine)
replaces the placeholders (i.e. '%SystemRoot%\system32'
is replaced by the current path 'C:\Windows\system32'
). Updating the PATH variable, I dont want to replace the placeholder with the path.
After SetEnvironmentVariable
no program can't be opened from the command box anymore (i.e. calc.exe in the command box doesn't work). Im using following code:
String oldPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("PATH", oldPath + ";%MYDIR%", EnvironmentVariableTarget.Machine);
After editing and changing the PATH
variable with Windows everything works again. (I thing changes are required, otherwise it is not overwritten)
You can edit existing environment variables or add, reset and unset new variables based on your project requirements. To globally change the system environment from the one in which Qt Creator is started, select Edit > Preferences > Environment > System, and then select Change in the Environment field.
Environment variables in PowerShell are stored as PS drive (Env: ). To retrieve all the environment variables stored in the OS you can use the below command. You can also use dir env: command to retrieve all environment variables and values.
You can use the registry to read and update:
string keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
//get non-expanded PATH environment variable
string oldPath = (string)Registry.LocalMachine.CreateSubKey(keyName).GetValue("Path", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
//set the path as an an expandable string
Registry.LocalMachine.CreateSubKey(keyName).SetValue("Path", oldPath + ";%MYDIR%", RegistryValueKind.ExpandString);
You can use WMI to retrieve the raw values (not sure about updating them though):
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Environment WHERE Name = 'PATH'");
foreach (ManagementBaseObject managementBaseObject in searcher.Get())
Console.WriteLine(managementBaseObject["VariableValue"]);
Check WMI Reference on MSDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With