2016-11-08 45 views
0

我正在編寫一個從註冊表加載參數的應用程序。這裏是我用來加載它的代碼:C#無法在LocalMachine中加載註冊表值

public bool getRegValues() //get values used for the SQL Connection etc 
    { 
     using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Company\Application\NightJob\", RegistryKeyPermissionCheck.ReadWriteSubTree)) 
     { 
      if (key != null) 
      { 
       this.serverName = key.GetValue("SQLserver").ToString(); 
       this.timeout = key.GetValue("timeout").ToString(); 
       this.Database = key.GetValue("database").ToString(); 
       this.logTable = key.GetValue("table_log").ToString(); 
       this.budgetTable = key.GetValue("table_budget").ToString(); 
       this.personsTable = key.GetValue("table_persons").ToString(); 
       this.tempTable = key.GetValue("table_temp").ToString(); 
       this.cashiersDB = key.GetValue("cashiersDB").ToString(); 
       this.customersTbl = key.GetValue("cashiersCustomersTable").ToString(); 

       key.SetValue("version", version); 
       if (this.serverName == null || this.timeout == null || this.Database == null || this.logTable == null 
        || this.budgetTable == null || this.personsTable == null || this.tempTable == null) 
       { 
        Console.WriteLine("One of the values could not be loaded."); 
        return false; 
       } 
      } 
      else 
      { 
       Console.WriteLine("Key is null."); 
       return false; 
      } 
      return true; 
     } 
    } 

當我在我的工作站上運行代碼時,一切都是完美的。當我在服務器上執行它時,它返回false並寫入「密鑰爲空」。

當我使用Registry.CurrentUser而不是Registry.LocalMachine編譯代碼時,它返回true(當然,不同位置的值是相同的)。

出了什麼問題?我是域管理員,並且還給了我明確的完全控制權限HKEY_LOCAL_MACHINE \ SOFTWARE \ Company \ Application \ NightJob \

任何想法?

回答

0

如果您使用的是.NET 4試試這個使用:

using(RegistryKey SoftwareKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"SOFTWARE\Company\Application\NightJob\", RegistryKeyPermissionCheck.ReadWriteSubTree)) 
+0

非常感謝你。這確實解決了這個問題。非常感謝 – josibu

+0

@josibu您的歡迎 – tdog