How to set a global environment variable in .NET Core (user-wide or system-wide)(如何在 .NET Core(用户范围或系统范围)中设置全局环境变量)
问题描述
在完整的 .NET 中,我们可以将 EnvironmentVariableTarget 枚举传递给 Environment.SetEnvironmentVariable 调用:
公共枚举 EnvironmentVariableTarget{过程,用户,机器}使用
User或Machine选项,我们可以设置用户范围或系统范围的变量,该变量在应用程序结束后仍然有效:Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.User);...
<代码>>回声%foo%酒吧但是,
<块引用>Environment.SetEnvironmentVariable不接受 .NET Core 中的变量目标.甚至这种方法的 XML 注释都说:创建、修改或删除存储在当前进程中的环境变量.
如何在面向 .NET Core 的应用程序中设置用户范围或机器范围的环境变量?只有跨平台解决方案才有意义(至少是 Windows 和 Linux).
解决方案对于 .NET Core 1.x,它只允许在用户上下文中设置环境变量.通过新的 .NET Core 2.0 预览版,它允许使用
<块引用>EnvironmentVariableTarget.但是,根据 this GitHub 问题设置用户或机器环境变量不起作用非windows平台.在非 Windows 平台上使用其他范围(例如用户、机器))未映射到实现中.
GitHub issue 中还描述了使用变通方法检查是否是非windows平台来设置环境变量.例如:
<上一页>//省略检查 bash 二进制文件的存在if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) System.Diagnostics.Process.Start("/bin/bash", "-c export" + 变量 + "=" + value);
In full .NET we can pass EnvironmentVariableTarget enum to Environment.SetEnvironmentVariable call:
public enum EnvironmentVariableTarget
{
Process,
User,
Machine
}
With User or Machine options we can set a user-wide or system-wide variable which stays live after application end:
Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.User);
...
> echo %foo%
bar
However, Environment.SetEnvironmentVariable doesn't accept the variable target in .NET Core. Even XML comment for this method says:
Creates, modifies, or deletes an environment variable stored in the current process.
How to set an user-wide or machine-wide environment variable in .NET Core-targeted app? Only a crossplatform solution makes sense (at least Windows and Linux).
For .NET Core 1.x it only allows setting an environment variable in the User context. With the new .NET Core 2.0 preview it allows using the EnvironmentVariableTarget. However, according to this GitHub issue setting User or Machine environment variables doesn't work on non-windows platforms.
Using other scopes (e.g. User, Machine) on non-Windows platforms) is not mapped in the implementation.
Also described in the GitHub issue is to use a workaround to check if it is a non-windows platform to set an environment variable. For example:
// omitting check for presence of bash binary
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) System.Diagnostics.Process.Start("/bin/bash", "-c export " + variable + "=" + value);
这篇关于如何在 .NET Core(用户范围或系统范围)中设置全局环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 .NET Core(用户范围或系统范围)中设置全局环境变量
基础教程推荐
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
