简体   繁体   English

使用环境变量启动进程

[英]Start process with environment variable

I want to start a process with the following path.我想用以下路径开始一个过程。

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

When I type this into the console the process starts as expected but when I try to do it in code I get the following exception:当我在控制台中输入此过程时,该过程按预期开始,但是当我尝试在代码中执行此操作时,出现以下异常:

the system cannot find the file specified系统找不到指定的文件

This I my code so far:这是我到目前为止的代码:

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

Does anybody have an idea if I can do this directly by giving the ProcessStartInfo class the environment variable or if I have to parse it before doing so?有人知道我是否可以通过为 ProcessStartInfo 类提供环境变量来直接执行此操作,或者我是否必须在这样做之前对其进行解析?

You should use this to get the path to Program Files:您应该使用它来获取程序文件的路径:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)

Special folders enum . 特殊文件夹 enum

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

This way you can use the variables (eg "%ProgramFiles(x86)% ) and not depend on the folder being in C:\\ or something.这样您就可以使用变量(例如"%ProgramFiles(x86)% )而不依赖于C:\\的文件夹或其他东西。

The constructor just sets the fileName property to what you pass, so yes you will need to resolve the environment variable first.构造函数只是将fileName属性设置为您传递的内容,所以是的,您需要先解析环境变量。

From the source code for ProcessStartInfo :ProcessStartInfo 的源代码

public ProcessStartInfo(string fileName) {
     this.fileName = fileName;
}

或者试试这个,如果你想要像开始->运行一样的行为

Environment.ExpandEnvironmentVariables("%windir%\System32")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM