使用环境变量启动进程
Start process with environment variable
我想用以下路径启动一个进程。
"ProgramFiles(x86)\Philips Speech\Device Control Center PDCC.exe"
当我在控制台中键入此内容时,进程会按预期启动,但当我尝试在代码中执行此操作时,出现以下异常:
the system cannot find the file specified
这是我目前的代码:
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
有人知道我是否可以通过给 ProcessStartInfo class 环境变量直接执行此操作,或者我是否必须在执行此操作之前对其进行解析?
构造函数只是将 fileName
属性 设置为您传递的内容,所以是的,您需要先解析环境变量。
来自the source code for ProcessStartInfo:
public ProcessStartInfo(string fileName) {
this.fileName = fileName;
}
string path = Environment.ExpanEnvironmentVariables("%ProgramFiles(x86)%\Philips Speech\Device Control Center PDCC.exe");
var startInfo = new ProcessStartInfo(path);
new Process(startInfo).Start();
这样您就可以使用变量(例如 "%ProgramFiles(x86)%
)而不依赖于 C:\
中的文件夹或其他内容。
您应该使用它来获取程序文件的路径:
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
或者试试这个,如果你想要像 Start->运行
一样的行为
Environment.ExpandEnvironmentVariables("%windir%\System32")
我想用以下路径启动一个进程。
"ProgramFiles(x86)\Philips Speech\Device Control Center PDCC.exe"
当我在控制台中键入此内容时,进程会按预期启动,但当我尝试在代码中执行此操作时,出现以下异常:
the system cannot find the file specified
这是我目前的代码:
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
有人知道我是否可以通过给 ProcessStartInfo class 环境变量直接执行此操作,或者我是否必须在执行此操作之前对其进行解析?
构造函数只是将 fileName
属性 设置为您传递的内容,所以是的,您需要先解析环境变量。
来自the source code for ProcessStartInfo:
public ProcessStartInfo(string fileName) {
this.fileName = fileName;
}
string path = Environment.ExpanEnvironmentVariables("%ProgramFiles(x86)%\Philips Speech\Device Control Center PDCC.exe");
var startInfo = new ProcessStartInfo(path);
new Process(startInfo).Start();
这样您就可以使用变量(例如 "%ProgramFiles(x86)%
)而不依赖于 C:\
中的文件夹或其他内容。
您应该使用它来获取程序文件的路径:
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
或者试试这个,如果你想要像 Start->运行
一样的行为Environment.ExpandEnvironmentVariables("%windir%\System32")