How To Set Scoped Environment Variables In C# & .NET
[C#, .NET]
In a previous post, “How To Read Environment Variables In C# & .NET”, we looked at how to read environment variables in C# & .NET.
In a subsequent post, “About Environment Variable Scopes”, we learned that environment variables are scoped.
In this post, we will look at how to write or set environment variables in C#.
Process Scoped Variables
To set process-scoped variables, we use the SetEnvironmentVariable method of the Environment class, specifying the scope via the EnvironmentVariableTarget enum.
Environment.SetEnvironmentVariable("Mood", "Happy", EnvironmentVariableTarget.Process);
This particular method works across operating systems - macOS, Windows, and Linux.
User Scoped Variables
To set user-scoped variables, pass the EnvironmentVariableTarget.User enum. It is important to note that this only works in Windows, as this information is stored in the Windows registry.
Environment.SetEnvironmentVariable("Mood", "Happy", EnvironmentVariableTarget.User);
Machine Scoped Variables.
To set machine-scoped variables, pass the EnvironmentVariableTarget.Machine enum. It is important to note that this only works in Windows, as this information is stored in the Windows registry.
Additionally, the process setting this variable must be elevated, as setting a machine-level environment variable requires administrative access.
Environment.SetEnvironmentVariable("Mood", "Happy", EnvironmentVariableTarget.Machine);
TLDR
The SetEnvironmentVariable() method has an overload that allows specification of the scope.
Happy hacking!