[英]How do I get and set Environment variables in C#?
如何获取环境变量,如果缺少某些内容,请设置值?
Use the System.Environment class.使用System.Environment类。
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
.可选参数
Target
是EnvironmentVariableTarget
类型的枚举,它可以是以下之一: Machine
、 Process
或User
。 If you omit it, the default target is the current process.如果省略它,则默认目标是当前进程。
I ran into this while working on a .NET console app to read the PATH environment variable, and found that using System.Environment.GetEnvironmentVariable will expand the environment variables automatically.我在使用 .NET 控制台应用程序读取 PATH 环境变量时遇到了这个问题,发现使用 System.Environment.GetEnvironmentVariable 会自动扩展环境变量。
I didn't want that to happen...that means folders in the path such as '%SystemRoot%\\system32' were being re-written as 'C:\\Windows\\system32'.我不希望这种情况发生……这意味着路径中的文件夹(例如“%SystemRoot%\\system32”)被重写为“C:\\Windows\\system32”。 To get the un-expanded path, I had to use this:
为了获得未扩展的路径,我不得不使用这个:
string keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
string existingPathFolderVariable = (string)Registry.LocalMachine.OpenSubKey(keyName).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
Worked like a charm for me.对我来说就像一种魅力。
Get and Set获取和设置
Get得到
string getEnv = Environment.GetEnvironmentVariable("envVar");
Set放
string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv);
This will work for an environment variable that is machine setting.这将适用于机器设置的环境变量。 For Users, just change to User instead.
对于用户,只需改为用户即可。
String EnvironmentPath = System.Environment
.GetEnvironmentVariable("Variable_Name", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("Variable name", value, EnvironmentVariableTarget.User);
In Visual Studio 2019 -- Right Click on your project, select Properties > Settings, Add a new variable by giving it a name (like ConnectionString), type, and value.在 Visual Studio 2019 中——右键单击您的项目,选择“属性”>“设置”,通过为其指定名称(如 ConnectionString)、类型和值来添加新变量。 Then in your code read it so:
然后在您的代码中阅读它:
var sConnectionStr = Properties.Settings.Default.ConnectionString;
These variables will be stored in a config file (web.config or app.config) depending upon your type of project.这些变量将存储在配置文件(web.config 或 app.config)中,具体取决于您的项目类型。 Here's an example of what it would look like:
下面是一个示例:
<applicationSettings>
<Testing.Properties.Settings>
<setting name="ConnectionString" serializeAs="String">
<value>data source=blah-blah;etc-etc</value>
</setting>
</Testing.Properties.Settings>
</applicationSettings>
I could be able to update the environment variable by using the following我可以使用以下方法更新环境变量
string EnvPath = System.Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine) ?? string.Empty;
if (!string.IsNullOrEmpty(EnvPath) && !EnvPath .EndsWith(";"))
EnvPath = EnvPath + ';';
EnvPath = EnvPath + @"C:\Test";
Environment.SetEnvironmentVariable("PATH", EnvPath , EnvironmentVariableTarget.Machine);
If the purpose of reading environment variable is to override the values in the appsetting.json or any other config file, you can archive it through EnvironmentVariablesExtensions .如果读取环境变量的目的是覆盖 appsetting.json 或任何其他配置文件中的值,您可以通过EnvironmentVariablesExtensions对其进行存档。
var builder = new ConfigurationBuilder()
.AddJsonFile("appSettings.json")
.AddEnvironmentVariables(prefix: "ABC_")
var config = builder.Build();
According to this example, Url for the environment is read from the appsettings.json.根据此示例,环境的 Url 是从 appsettings.json 中读取的。 but when the
AddEnvironmentVariables(prefix: "ABC_")
line is added to the ConfigurationBuilder the value appsettings.json will be override by in the environement varibale value.但是当
AddEnvironmentVariables(prefix: "ABC_")
行添加到 ConfigurationBuilder 时,值 appsettings.json 将被环境变量值覆盖。
Environment variables can also be placed in an application's app.config
or web.config
file, by their name bounded with percentages ( %
), and then expanded in code.环境变量也可以放置在应用程序的
app.config
或web.config
文件中,它们的名称以百分比 ( %
) 为界,然后在代码中展开。
For example, in app.config
:例如,在
app.config
:
<connectionStrings>
<add name="myConnectionString" connectionString="%DEV_SQL_SERVER_CONNECTION_STRING%" providerName="System.Data.SqlClient" />
</connectionStrings>
And then in the code:然后在代码中:
string connectionStringEnv = ConfigurationManager.AppSettings["myConnectionString"];
string connectionString = System.Environment.ExpandEnvironmentVariables(connectionStringEnv);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.