使用WHERE命令chrome.exe
作为参数。这将告诉您将由 shell 加载的可执行文件的路径。
您只需要读回命令的输出。
这与您当前的版本一样,假定可执行文件位于系统 PATH 中。
这是一些您可以根据需要定制的代码。它本质上包装了 WHERE 命令(顺便说一句,它是一个可执行文件,因此WHERE WHERE
将显示其路径)。
using System;
using System.Diagnostics;
public sealed class WhereWrapper
{
private static string _exePath = null;
public static int Main(string[] args) {
int exitCode;
string exeToFind = args.Length > 0 ? args[0] : "WHERE";
Process whereCommand = new Process();
whereCommand.OutputDataReceived += Where_OutputDataReceived;
whereCommand.StartInfo.FileName = "WHERE";
whereCommand.StartInfo.Arguments = exeToFind;
whereCommand.StartInfo.UseShellExecute = false;
whereCommand.StartInfo.CreateNoWindow = true;
whereCommand.StartInfo.RedirectStandardOutput = true;
whereCommand.StartInfo.RedirectStandardError = true;
try {
whereCommand.Start();
whereCommand.BeginOutputReadLine();
whereCommand.BeginErrorReadLine();
whereCommand.WaitForExit();
exitCode = whereCommand.ExitCode;
} catch (Exception ex) {
exitCode = 1;
Console.WriteLine(ex.Message);
} finally {
whereCommand.Close();
}
Console.WriteLine("The path to {0} is {1}", exeToFind, _exePath ?? "{not found}");
return exitCode;
}
private static void Where_OutputDataReceived(object sender, DataReceivedEventArgs args) {
if (args.Data != null) {
_exePath = args.Data;
}
}
}