2011-12-01 110 views
0
public static bool IsApplictionInstalled(string p_name) 
    { 
     string displayName; 
     RegistryKey key; 

     // search in: CurrentUser 
     key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); 
     foreach (String keyName in key.GetSubKeyNames()) 
     { 
      RegistryKey subkey = key.OpenSubKey(keyName); 
      displayName = subkey.GetValue("DisplayName") as string; 
      if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true) 
      { 
       return true; 
      } 
     } 

     // search in: LocalMachine_32 
     key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); 
     foreach (String keyName in key.GetSubKeyNames()) 
     { 
      RegistryKey subkey = key.OpenSubKey(keyName); 
      displayName = subkey.GetValue("DisplayName") as string; 
      if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true) 
      { 
       return true; 
      } 
     } 

     // search in: LocalMachine_64 
     key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"); 
     foreach (String keyName in key.GetSubKeyNames()) 
     { 
      RegistryKey subkey = key.OpenSubKey(keyName); 
      displayName = subkey.GetValue("DisplayName") as string; 
      if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true) 
      { 
       return true; 
      } 
     } 

     // NOT FOUND 
     return false; 
    } 

該方法檢查32位或64位Win OS中的軟件,但其無法正常工作,在key.GetSubKeyNames()中的字符串keyName處粉碎,未將對象引用設置爲對象的實例。任何一個可以告訴我是什麼原因,如何檢查軟件是否安裝在C#中?

+0

也許鍵不存在? – ChrisBint

+0

除此之外,如果事情已經gobe可怕的錯誤,卸載鍵是否存在等,並不意味着它的安裝... –

+2

請永遠不要硬編碼'Wow6432Node'到應用程序中。如果您的目標是.net 4,則可以使用RegistryView'枚舉打開註冊表的32位或64位視圖。 –

回答

1

的錯誤意味着OpenSubKey返回null(你得到一個NullReferenceException當您試圖訪問一個變量組的成員null)。這反過來意味着您正在查找的註冊表項不存在。

嘗試使用key對象之前添加null檢查。

key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); 
if(key != null) 
{ 
    foreach (String keyName in key.GetSubKeyNames()) 
    { 
     // .... 
    } 
} 
+0

我嘗試了,我跑我的代碼,我已經安裝Skype,但這種方法始終返回false – Desire

+0

@Aqib:什麼我知道,不是每一個軟件,你的註冊表中的一部分安裝場所的關鍵...... – Marco

+0

你問關於錯誤,儘管你的標題與你的問題不同。從註冊表中讀取時,需要確保運行該程序的帳戶有權從註冊表中讀取。 – Oded

4

我想這個問題可能是在這裏:

key = Registry.LocalMachine.OpenSubKey(
      @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"); 
foreach (String keyName in key.GetSubKeyNames()) 

該鍵不存在32位。
所以,你應該使用(每一個鍵就檢查)

key = .... 
if (key != null) 
{ 
    foreach (String keyName in key.GetSubKeyNames()) 
    // .... 
} 

另一種信息:你會注意到一些(很多?)註冊表項不包含displayName價值,所以你的比較可能會失敗。嘗試(僅舉例)使用密鑰名稱代替displayName(如果不存在)。