C#:看不到 windows 注册表中的更改

C#: Cannot see the changes in the windows registry

没有错误,没有异常,什么都没有。一切似乎都很好,除了注册表保持原样。

   class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Edit();
            }
            catch (Exception)
            {
                Restore(); // not included in the sample for simplicity
            }
        }

        public static void  Edit()
        {
            Microsoft.Win32.RegistryKey Login;
            Login = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(ConfigurationManager.AppSettings["Login"].ToString());
            Login.SetValue("ServerName", ConfigurationManager.AppSettings["ServerName"].ToString());
            Login.SetValue("ImageServerName", ConfigurationManager.AppSettings["ImageServerName"].ToString());
            Login.Close();

            Microsoft.Win32.RegistryKey Login2;
            Login2 = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(ConfigurationManager.AppSettings["Wow6432NodeLogin"].ToString());
            Login2.SetValue("ServerName", ConfigurationManager.AppSettings["Wow6432NodeServerName"].ToString());
            Login2.SetValue("ImageServerName", ConfigurationManager.AppSettings["Wow6432NodeImageServerName"].ToString());
            Login2.Close();
        }
}

我认为某处有误。但不会抛出异常。 catch 块永远不会被击中。

我是 运行 它的管理员。我什至 运行 它没有管理员权限,但当它应该显示 "access denied" 或其他东西时仍然没有错误。我重新启动笔记本电脑以查看应用的更改,但仍然没有成功。

我用这段代码读取了最近添加的值,我可以看到键。但是不知何故,这些更改没有被应用。

        Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(ConfigurationManager.AppSettings["Login"].ToString());
        Object o = key.GetValue("ServerName");
        Console.WriteLine(o.ToString());

我正在使用 .Net 4.5.2,为 Any CPU 构建,所以:Windows 7.

我需要提交更改什么的吗?

正如@PieterWitvoet 在评论中所建议的,您可能想要使用 OpenBaseKey() instead. This is to avoid WoW64 registry redirection as explained here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa384182.aspx

请注意该页末尾的小字:

To examine the effect of running this example with regedit, inspect the values of the following keys. Note that applications should avoid using Wow6432Node in hard-coded registry paths.

因此,这是您可以改为执行的示例:

static void Edit()
{
    using (var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
    using (RegistryKey key = root.CreateSubKey("SOFTWARE\Homebrew-Testing"))
    {
        key.SetValue("ServerName", "ServerName-Value");
        key.SetValue("ImageServerName", "ImageServerName-Value");
    }
}

请注意如何放弃专门处理 Wow6432Node 的代码的第二部分,上面链接的文章中建议不要这样做。

RegistryView 的文档指出,如果您在 32 位操作系统上请求 64 位视图,则返回的密钥将在 32 位视图中。

希望对您有所帮助。祝你好运。