简体   繁体   中英

How do I use C# to get the path to chrome.exe on Windows?

I want to launch chrome from my automated test framework so that I can test my server-side ASP.NET code. What's the best way to determine the location of where chrome.exe is located on my computer?

When Chrome is installed on a computer, it installs the ChromeHTML URL protocol. You could use that to get to the path for Chrome.exe.

Some example code may help. The following code returns a string that looks like this:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -- "%1"

Example code to get that:

var path = Microsoft.Win32.Registry.GetValue(
    @"HKEY_CLASSES_ROOT\ChromeHTML\shell\open\command", null, null) as string;
if (path != null)
{
    var split = path.Split('\"');
    path = split.Length >= 2 ? split[1] : null;
}

if path is null at the end of the code snippet, then you can assume Chrome isn't installed.

Another approach is use the logic used by the Karma test framework.

const string suffix = @"Google\Chrome\Application\chrome.exe";
var prefixes = new List<string> {Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)};
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
var programFilesx86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
if (programFilesx86 != programFiles)
{
    prefixes.Add(programFiles);
}
else
{
    var programFilesDirFromReg = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion", "ProgramW6432Dir", null) as string;
    if (programFilesDirFromReg != null) prefixes.Add(programFilesDirFromReg);
}

prefixes.Add(programFilesx86);
var path = prefixes.Distinct().Select(prefix => Path.Combine(prefix, suffix)).FirstOrDefault(File.Exists);

if path is null at the end of the code snippet, then you can assume Chrome isn't installed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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