2013-04-22 98 views
0

我想開發一種方法來讀取機器上安裝的程序。C#異常讀取註冊表:空引用異常

public void refreshProgramsFromWindows() { 
      string SoftwareKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products"; 
      RegistryKey rk = default(RegistryKey); 
      rk = Registry.LocalMachine.OpenSubKey(SoftwareKey); 
      //string skname = null; 
      string sname = string.Empty; 

      // New list from scratch 
      this.installedSoftwareList = new List<software>(); 

      // Object software info 
      software aSoftware = new software(); 

      foreach (string skname in rk.GetSubKeyNames()) 
      { 

       // Reset software info 
       aSoftware.reset(); 

       try 
       { 
        // Name of the programm 
        sname = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("DisplayName").ToString(); 
        aSoftware.name = sname; 

        // Write program to the list 
        installedSoftwareList.Add(aSoftware); 
       } 
       catch (Exception ex) 
       { 

       } 
      } 

網絡框架是4.5,我在Windows 7/8。當我調試這段代碼var rk爲null時,它在foreach中引發一個空引用異常。應用程序清單設置爲需要管理員權限,所以註冊表是可讀的。問題是什麼?

非常感謝您。 乾杯。

+0

http://stackoverflow.com/questions/1268715/registry-localmachine-opensubkey-returns-null – OldProgrammer 2013-04-22 02:19:06

回答

3

64位的註冊表問題:

新增(可處理64位註冊表):

public static RegistryKey GetRegistryKey() 
     { 
      return GetRegistryKey(null); 
     } 

     public static RegistryKey GetRegistryKey(string keyPath) 
     { 
      RegistryKey localMachineRegistry 
       = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, 
              Environment.Is64BitOperatingSystem 
               ? RegistryView.Registry64 
               : RegistryView.Registry32); 

      return string.IsNullOrEmpty(keyPath) 
       ? localMachineRegistry 
       : localMachineRegistry.OpenSubKey(keyPath); 
     } 

     public static object GetRegistryValue(string keyPath, string keyName) 
     { 
      RegistryKey registry = GetRegistryKey(keyPath); 
      return registry.GetValue(keyName); 
     } 

而改變:

rk = Registry.LocalMachine.OpenSubKey(SoftwareKey); 

rk = GetRegistryKey(SoftwareKey); 

而現在作品。