使用环境变量启动进程

NtF*_*reX 2 c# process environment-variables

我想用以下路径开始一个过程。

“ProgramFiles(x86)\Philips Speech\Device Control Center PDCC.exe”

当我在控制台中输入此过程时,该过程按预期开始,但是当我尝试在代码中执行此操作时,出现以下异常:

该系统找不到指定的文件

这是我到目前为止的代码:

var startInfo = new ProcessStartInfo("%ProgramFiles(x86)%\Philips Speech\Device Control Center PDCC.exe");
Debug.Assert(startInfo.EnvironmentVariables.ContainsKey("ProgramFiles(x86)")) //Is true
new Process(startInfo).Start(); //<- exception occures here
Run Code Online (Sandbox Code Playgroud)

有人知道我是否可以通过为 ProcessStartInfo 类提供环境变量来直接执行此操作,或者我是否必须在这样做之前对其进行解析?

小智 7

string path = Environment.ExpanEnvironmentVariables("%ProgramFiles(x86)%\Philips Speech\Device Control Center PDCC.exe");
var startInfo = new ProcessStartInfo(path);
new Process(startInfo).Start(); 
Run Code Online (Sandbox Code Playgroud)

这样您就可以使用变量(例如"%ProgramFiles(x86)%)而不依赖于所在的文件夹C:\或其他东西。


Que*_*ger 5

您应该使用它来获取程序文件的路径:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
Run Code Online (Sandbox Code Playgroud)

特殊文件夹 enum