Home >Backend Development >C++ >How do I Get and Set Environment Variables in C#?

How do I Get and Set Environment Variables in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-18 18:27:40110browse

How do I Get and Set Environment Variables in C#?

Working with 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn