c# - 如何安全地附加到 ProcessStartInfo.EnvironmentVariables ["PATH"]

标签 c# .net-core process environment-variables

我目前正在将一个 C# 应用程序从 .NET Framework 移植到 .NET Core,以便能够在 Linux 上运行它。在某个时候,此应用程序使用 System.Diagnostics.Process 类在单独的进程中启动另一个程序。虽然这在一般情况下运行良好,但该特定程序需要使用修改后的 PATH 环境变量运行。这是我为 Windows 所做的(为在 Linux 上测试而更改的路径):

string directory = "/tmp";
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
    Arguments = "-c \"echo $PATH\"",
    FileName = "/bin/bash",
};
processStartInfo.EnvironmentVariables["PATH"] += ";" + directory;
Process.Start(processStartInfo);

不幸的是,Linux 使用冒号(“:”)作为路径分隔符,因此程序生成

/usr/local/bin:/usr/bin:/bin:/usr/games;/tmp

而不是想要的输出

/usr/local/bin:/usr/bin:/bin:/usr/games:/tmp

我现在的问题是:如何以安全、跨平台的方式正确更新 PATH 变量?是否有一些系统相关的属性来检索分隔符(如 Environment.NewLine 用于换行符或 Path.DirectorySeparatorChar 用于斜杠),或者我是否必须检查手动当前操作系统?

最佳答案

This应该是你需要的:

processStartInfo.EnvironmentVariables["PATH"] += Path.PathSeparator + directory;

关于c# - 如何安全地附加到 ProcessStartInfo.EnvironmentVariables ["PATH"],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57362291/

相关文章:

shell - 我如何知道 bash Kill 是否会使用 pid 还是 jobspec?

c# - 无论如何将 RDL 报告内容加载到 WPF FlowDocument 或类似文件中?

c# - 使用 MVC、MVP、MVVM 的真实 winforms/wpf 项目

c# - 为什么使用 ExecutionAndPublication 的 Lazy<T> 与生成的 IEnumerables 行为不同?

c# - 由于超时已到.net core,执行 DbCommand 失败

c# - 局域网唤醒 - Linux - .Net Core

c# - 在 using 语句中操作流

linux - 了解 Linux 中 execve 内部结构的最佳方法是什么?

linux - 获取子进程列表,在 Linux 中由父进程运行

c# - 键值未知时反序列化 JSON