2013-04-22 2 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) 
       { 

       } 
      } 

Net Framework 4.5, и я над Windows 7/8. Когда я отлаживаю этот кусок кода var rk равным NULL, и он бросает исключение нулевой ссылки в foreach. В манифесте приложения установлено требование привилегий администратора, поэтому реестр доступен для чтения. В чем проблема?

Спасибо вам заранее. Cheers.

+0

http://stackoverflow.com/questions/1268715/registry-localmachine-opensubkey-returns-null – OldProgrammer

ответ

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); 

И теперь это работает.