1. 程式人生 > 實用技巧 >如何獲取chrome.exe路徑(c#)

如何獲取chrome.exe路徑(c#)

啟動本機chrome瀏覽器可以直接使用

System.Diagnostics.Process.Start("chrome.exe");

但是當程式以管理員許可權啟動後(如何以管理員許可權啟動參考c#程式以管理員許可權執行),上述程式碼可能會失效(測試環境win10+vs2019,其他環境未測試),提示“系統找不到指定檔案”,這裡就需要指定chrome.exe的全路徑,現在提供兩種方法獲取chrome.exe的路徑

1、通過登錄檔HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths(這個不是一定能找到,本機測試時該路徑下沒有chrome.exe的資訊)

絕大多數軟體,基本上都會在登錄檔中記錄自己的名字和安裝路徑資訊。

在登錄檔中記錄這些資訊的位置是:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths

因此,我們只要能訪問到登錄檔的這個位置,就可以獲取到某些軟體的名稱和安裝路徑資訊。

 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安裝在計算機上時,它會安裝ChromeHTMLURL協議。您可以使用它來到Chrome.exe的路徑。

一些示例程式碼可能會有所幫助。下面的程式碼返回一個字串,它看起來像這樣:

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

登錄檔路徑為

@"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         }