2017-10-04 125 views
0

我一直在尋找一段時間,但還沒有找到任何東西。C#向註冊表添加字符串

它有效,但不完全。它查找註冊表中的文件夾,但不會創建字符串。我沒有得到關於權限或類似的錯誤。我以管理員身份運行。

  try 
     { 
      RegistryKey registryKey = Registry.LocalMachine; 
      registryKey.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\OEMInformation", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryOptions.None); 

      registryKey.SetValue("Test1","Test2"); 
      registryKey.Close(); 

      return true; 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.ToString()); 
      return false; 
     } 

我在做什麼錯?或者我錯過了一些重要的東西?

感謝 DaNeubi

+3

好像你正試圖設置'Test1'上LocalMachine'的'根 - 您需要捕獲CreateSubKey'的'結果,然後做'SetValue'在那 –

回答

0

感謝@ stephen.vakil我能解決它。

這裏是我的代碼現在:

 public static Boolean WriteToRegistry(String[] OEMInformations) 
    { 
     try 
     { 
      for (int i = 0; i < OEMInformations.Length; i = i +2) 
      { 
       RegistryKey mainKey = Registry.LocalMachine; 
       RegistryKey firstKey = mainKey.OpenSubKey("SOFTWARE", true); 
       RegistryKey secondKey = firstKey.OpenSubKey("Microsoft", true); 
       RegistryKey thirdKey = secondKey.OpenSubKey("Windows", true); 
       RegistryKey fourthKey = thirdKey.OpenSubKey("CurrentVersion", true); 
       RegistryKey fifthKey = fourthKey.OpenSubKey("OEMInformation", true); 

       fifthKey.SetValue(OEMInformations[i],OEMInformations[i + 1], RegistryValueKind.String); 

       fifthKey.Close(); 
       fourthKey.Close(); 
       thirdKey.Close(); 
       secondKey.Close(); 
       firstKey.Close(); 
       mainKey.Close(); 
      } 
      return true; 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.ToString()); 
      return false; 
     } 
    }