C#向注册表添加一个字符串

时间:2017-10-04 18:32:23

标签: c# registry

我现在已经找了一段时间但是找不到任何东西。

它有效但不完全。它在注册表中找到文件夹,但它不会创建一个String。我没有收到有关权限或类似内容的任何错误。我是以管理员身份运行它。

            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

1 个答案:

答案 0 :(得分: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;
        }
    }
相关问题