Home >Backend Development >C++ >How do I Get and Set Environment Variables in C#?
The System.Environment
class in C# simplifies accessing and modifying environment variables. Two core methods facilitate this:
GetEnvironmentVariable(variableName [, targetScope])
: This retrieves the value associated with a specified environment variable. The optional targetScope
argument defines the variable's scope (Machine, Process, or User).SetEnvironmentVariable(variableName, value [, targetScope])
: This sets or updates the value of an environment variable. Similar to GetEnvironmentVariable
, targetScope
determines the variable's reach.Practical Examples:
Retrieving the "PATH" environment variable:
<code class="language-csharp">string pathVariable = System.Environment.GetEnvironmentVariable("PATH");</code>
Setting the "MyVar" environment variable to "MyValue" within the current process:
<code class="language-csharp">System.Environment.SetEnvironmentVariable("MyVar", "MyValue", EnvironmentVariableTarget.Process);</code>
Understanding Variable Scope:
The targetScope
parameter is crucial:
EnvironmentVariableTarget.Machine
: Modifies the system-wide environment variable. Requires administrator privileges.EnvironmentVariableTarget.Process
: Changes the variable only for the current application's process.EnvironmentVariableTarget.User
: Alters the environment variable for the currently logged-in user. Requires administrator privileges.If targetScope
is omitted, the default scope is the current process.
The above is the detailed content of How do I Get and Set Environment Variables in C#?. For more information, please follow other related articles on the PHP Chinese website!