How to set Environment variables permanently in C#
While the program is running, after using Set, the value is returned
using Get without any issue. The problem is the environment variable
isn't permanent (being set on the system).
Thats because the overload of SetEnvironmentVariable
that you're using stores in the process variables. From the docs:
Calling this method is equivalent to calling the
SetEnvironmentVariable(String, String, EnvironmentVariableTarget)
overload with a value of EnvironmentVariableTarget.Process for the
target argument.
You need to use the overload specifying EnvironmentVariableTarget.Machine
instead:
public static void Set(string name, string value)
{
Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.Machine);
}
How do I get and set Environment variables in C#?
Use the System.Environment class.
The methods
var value = System.Environment.GetEnvironmentVariable(variable [, Target])
and
System.Environment.SetEnvironmentVariable(variable, value [, Target])
will do the job for you.
The optional parameter Target
is an enum of type EnvironmentVariableTarget
and it can be one of: Machine
, Process
, or User
. If you omit it, the default target is the current process.
Get environment variables of a different process
Within links posted I found Oleksiy Gapotchenko's blog. He developed a ready-to-use nuget package.
Reads environment variables of a process. The functionality is
achieved by reading the process environment block (PEB) at the
operating system level.
blog.gapotchenko/reading-environment-variables
github/Gapotchenko.FX.Diagnostics.Process
nuget/packages/Gapotchenko.FX.Diagnostics.Process
How to Create,set,Read and Delete environment variable using C# and VB.Net programming languages
You can use Environment.SetEnvironmentVariable
to create, modify or delete environment variable andEnvironment.GetEnvironmentVariable
for retrieve it.
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.environment.setenvironmentvariable?view=netframework-4.7.2
To delete you set it to null.
Get environment variables of a different service
You can get the environment variables from the service manifest but these can be overridden in the application manifest.
This doesn't take into account Environment variables the service creates at runtime.
var client = new FabricClient();
var serviceManifest = await client.ServiceManager.GetServiceManifestAsync("Application1Type", "1.0.0",
"Service1Pkg");
var environmentVariables = XDocument.Parse(serviceManifest)
.Descendants()
.Where(x => x.Name == XName.Get("EnvironmentVariable", "http://schemas.microsoft.com/2011/01/fabric"))
.Select( x => new
{
Name = x.FirstAttribute.Value,
Value = x.LastAttribute.Value
})
.ToList();
How to set environment variable Path using C#
You are associating the environment variable with your program, but instead you want to associate it with your local machine in order to make it available to every program. Look at the overload that takes an EnvironmentVariableTarget
.
var name = "PATH";
var scope = EnvironmentVariableTarget.Machine; // or User
var oldValue = Environment.GetEnvironmentVariable(name, scope);
var newValue = oldValue + @";C:\Program Files\MySQL\MySQL Server 5.1\bin\\";
Environment.SetEnvironmentVariable(name, newValue, scope);
Visual Studio 2022 System.Environment.GetEnvironmentVariable not working
I'm assuming that you are using Visual Studio 2022 because you are using .NET 6 and the minimal host (i.e., no Startup.cs
)?
The general preference is not to store information in the Environment Variables given that this information is often uploaded to GitHub and can be trawled and used against you.
For a local development secret, the preference is to store these using the secrets.json
file. There is information on how to do this at Safe Storage of Secrets, as well as details on accessing Configuration files at Accessing Configuration File Information.
For the TL;DR: Crowd the steps below might help (this is what I did in my Blazor app with .NET 6):
- In Visual Studio 2022, right click on the project in question and select 'Manage User Secrets'. This will create a local
secrets.json
file and open it. It will also add a GUID in your project tile forUserSecretsId
. - Create your secrets as JSON key value pairs in this file as you would for environment variables.
- Go to 'Connected Services' in your project and configure the
Secrets.json
service. - Add the 'User Secrets' to your configuration file; this will depend on exactly where this is happening.
- Inject the
IConfiguration
into your controller and save this to a field. - Call the data you want using:
{yourConfigurationFieldName}.GetValue<string>({yourJsonKey})
Related Topics
C# VS Java Enum (For Those New to C#)
Printing All Contents of Array in C#
Calling Async Method Synchronously
Web App Blocked While Processing Another Web App on Sharing Same Session
How to Parse Huge JSON File as Stream in JSON.Net
Mod of Negative Number Is Melting My Brain
Remove Weird Characters ( a with Hat) from SQL Server Varchar Column
How to Use Global Variables in C#
How to Check If a Type Is a Subtype or the Type of an Object
Most Elegant Way to Generate Prime Numbers
Reading Email Using Pop3 in C#
Get Connection String from App.Config
Creating a Copy of an Object in C#
How to Get Dropdownlist Selectedvalue in Controller in MVC
Entity Framework 4 - Addobject VS Attach
What Is the Correct Way to Use JSON.Net to Parse Stream of JSON Objects