System.Diagnostics.Process ();StartInfo.参数使用环境变量作为参数

本文关键字:参数 环境变量 StartInfo Process Diagnostics System | 更新日期: 2023-09-27 18:19:00

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

程序:资源管理器参数:/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();

System.Diagnostics.Process ();StartInfo.参数使用环境变量作为参数

正如注释者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%表达式解析为环境变量解引用。