Home >Backend Development >C++ >How Do I Access and Modify Environment Variables in C#?
Access and modify environment variables in C#
Accessing and modifying environment variables is crucial in various programming scenarios. Here’s how to do it in C#:
Get environment variables:
To get the value of an environment variable, use the System.Environment
method of the GetEnvironmentVariable
class. For example:
<code class="language-csharp">var value = System.Environment.GetEnvironmentVariable("PATH");</code>
If the specified variable does not exist, this method will return null.
Set environment variables:
To set or modify environment variables, use the SetEnvironmentVariable
method:
<code class="language-csharp">System.Environment.SetEnvironmentVariable("MY_NEW_VARIABLE", "SomeValue");</code>
By default, changes only apply to the current process. To change variables for other targets (such as computers or users), specify the desired EnvironmentVariableTarget
enumeration as the third argument. For example:
<code class="language-csharp">System.Environment.SetEnvironmentVariable("MY_NEW_VARIABLE", "SomeValue", EnvironmentVariableTarget.Machine);</code>
Note: Variables set for the current process are only available within that process. Modifications to environment variables outside the scope of the process require elevated privileges.
The above is the detailed content of How Do I Access and Modify Environment Variables in C#?. For more information, please follow other related articles on the PHP Chinese website!