Home > Backend Development > C++ > How Do I Access and Modify Environment Variables in C#?

How Do I Access and Modify Environment Variables in C#?

Susan Sarandon
Release: 2025-01-18 18:17:10
Original
525 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template