简体   繁体   English

如何在 C# 中获取和设置环境变量?

[英]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 .可选参数TargetEnvironmentVariableTarget类型的枚举,它可以是以下之一: MachineProcessUser 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.configweb.config文件中,它们的名称以百分比 ( % ) 为界,然后在代码中展开。

  • Note that when a value of an environment variable is changed (or a new one is set), Visual Studio should be closed and reopened.请注意,当环境变量的值发生更改(或设置了新的值)时,应关闭并重新打开 Visual Studio。

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.

相关问题 环境变量如何知道我在什么环境上运行以及如何在 C# 中设置它们? - How do environment variables know what environment I am running on and how do I set them in C#? 如何在C#中永久设置环境变量 - How to set Environment variables permanently in C# 使用 C# 如何使用表单设置变量? - using C# how do i set variables using a Form? 如何在VS2019中为C#设置环境变量 - How to set environment variables for C# in VS2019 我该如何替换PATH环境变量以在C#中使用空格将那些变量加双引号和反斜杠? - How do I replace PATH Environment variables to double quote + backslashes those which have spaces in C#? 我如何确保C#的Process.Start将扩展环境变量? - How do I ensure C#'s Process.Start will expand environment variables? 如何在Visual Studio 2010中设置环境变量? - How do I set Environment Variables in Visual Studio 2010? 如何在C#中使用get和set? - How do I use get and set in C#? 如何在 C# 中的 AWS Lambda 项目中设置和获取环境变量 - How do I set & fetch Environment variable in AWS Lambda Project in C# 如何设置环境来解决 Visual Studio 中的 LeetCode 问题? C# - How do I set up an environment to solve LeetCode problems in Visual Studio? C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM