c# - 系统.诊断.进程(); StartInfo.Arguments 使用环境变量作为参数

标签 c# environment-variables system.diagnostics

如何将环境变量作为参数传递给 System.Diagnostics.Process()?由于某种原因使用变量路径失败。 例如,我尝试在路径 %windir% 打开资源管理器,但失败:

程序:explorer.exe 参数:/n、/e、%windir%

var f = new System.Diagnostics.Process();
f.StartInfo.WorkingDirectory = Path.GetDirectoryName(Program);
f.StartInfo.FileName = Program;
f.StartInfo.Arguments = !string.IsNullOrWhiteSpace(Params) ? Params : null;
f.Start();

最佳答案

正如评论者 Hans Passant 所说,像 %windir% 这样的语法是特定于命令行处理器的。您可以通过调用 Environment.GetEnvironmentVariable("windir") 在自己的代码中模拟它(即获取 WINDIR 环境变量的当前值),或 Environment.GetFolderPath(SpecialFolder.Windows)(即让 Windows 报告已知特殊文件夹的路径)。

如果您想让命令行处理器完成工作,您需要运行命令行处理器。例如:

f.StartInfo.FileName = "cmd.exe";
f.StartInfo.Arguments = "/c explorer.exe /n /e /select,%windir%";

这将运行 cmd.exe,而后者又会代表您启动 explorer.exe 进程,解析 %windir%表达式作为环境变量取消引用。

关于c# - 系统.诊断.进程(); StartInfo.Arguments 使用环境变量作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33286268/

相关文章:

c# - 来自一组 n 算法的 k 个对象的排列

C# DLLImport for C++ dll

c# - 如何为 WPF 属性制作模板?

c# - 跟踪日志位置,在哪里查看它们

memory-leaks - 如何解决 System.Diagnostics.PerformanceCounter 引起的内存泄漏

c# - 验证摘要应显示在警告消息框中?

c++ - ValueError : ['path' ] when installing pyfim

javascript - 从 Angular Controller 访问 Rails 环境变量

c# - 我的进程在等待输入吗?

bash - 为什么用 "envsubst <file >file"重写一个文件会留空?