啟動本機chrome瀏覽器可以直接使用
System.Diagnostics.Process.Start("chrome.exe");
但是當程序以管理員權限啟動后(如何以管理員權限啟動參考c#程序以管理員權限運行),上述代碼可能會失效(測試環境win10+vs2019,其他環境未測試),提示“系統找不到指定文件”,這里就需要指定chrome.exe的全路徑,現在提供兩種方法獲取chrome.exe的路徑
1、通過注冊表HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths(這個不是一定能找到,本機測試時該路徑下沒有chrome.exe的信息)
絕大多數軟件,基本上都會在注冊表中記錄自己的名字和安裝路徑信息。
在注冊表中記錄這些信息的位置是:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
因此,我們只要能訪問到注冊表的這個位置,就可以獲取到某些軟件的名稱和安裝路徑信息。
1 public string GetChromePath1(string exeName) 2 { 3 try 4 { 5 string app = exeName; 6 RegistryKey regKey = Registry.LocalMachine; 7 RegistryKey regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\" + app, false); 8 object objResult = regSubKey.GetValue(string.Empty); 9 RegistryValueKind regValueKind = regSubKey.GetValueKind(string.Empty); 10 if (regValueKind == Microsoft.Win32.RegistryValueKind.String) 11 { 12 return objResult.ToString(); 13 } 14 return ""; 15 } 16 catch 17 { 18 return ""; 19 } 20 }
2、通過ChromeHTML協議尋找
當Chrome安裝在計算機上時,它會安裝ChromeHTML URL協議,可以使用它來到Chrome.exe的路徑。
ChromeHTML URL協議注冊表路徑為:
@"HKEY_CLASSES_ROOT\" + "ChromeHTML" + @"\shell\open\command"
需要注意的是上述字符串中間的"ChromeHTML"在有的電腦上是"ChromeHTML.QUDJD3GQ5B7NKKR7447KSMQBRY",所以采用以下代碼獲取:
1 public string GetChromePath() 2 { 3 RegistryKey regKey = Registry.ClassesRoot; 4 string path = ""; 5 string chromeKey = ""; 6 foreach (var chrome in regKey.GetSubKeyNames()) 7 { 8 if (chrome.ToUpper().Contains("CHROMEHTML")) 9 { 10 chromeKey = chrome; 11 } 12 } 13 if (!string.IsNullOrEmpty(chromeKey)) 14 { 15 path = Registry.GetValue(@"HKEY_CLASSES_ROOT\" + chromeKey + @"\shell\open\command", null, null) as string; 16 if (path != null) 17 { 18 var split = path.Split('\"'); 19 path = split.Length >= 2 ? split[1] : null; 20 } 21 } 22 return path; 23 }