Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetEnvironmentVariable() and SetEnvironmentVariable() for PATH Variable

I want to extend the current PATH variable with a C# program. Here I have several problems:

  1. 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.

  2. 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)

like image 216
Freddy Avatar asked Aug 19 '11 12:08

Freddy


People also ask

How do I set environment variables in Qt?

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.

How do I display environment variables in PowerShell?

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.


2 Answers

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);
like image 197
Sabri Sawaad Avatar answered Sep 20 '22 14:09

Sabri Sawaad


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

like image 21
Strillo Avatar answered Sep 16 '22 14:09

Strillo