注册表键值明明存在OpenSubKey始终返回null,解决方案

Posted 随风任飘遥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了注册表键值明明存在OpenSubKey始终返回null,解决方案相关的知识,希望对你有一定的参考价值。

先上代码及实例
RegistryKey rsg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Macromedia\FlashPaper Printer\2\Installation\", false);
为什么返回值是NULL
技术分享L
原因其实是在64位电脑上跑32位程序,以上代码读取为空值,32位电脑读注册表使用OpenSubKey是正确的
解决方法:

I will show you how to get connecting string stored in registry. The code which I will show in this blog will work both on 32 and 64 bit machines. Let‘s say your connectingstring key name is "MyAppConnectionStringKey" and stored at following path "SOFTWARE\MyApp\Settings" with following value "Initial Catalog=mydb;Server=MY-PC;User ID=sa;Password=test"

技术分享

技术分享

Goal:
To get the "MyAppConnectionStringKey" value via code.

Solution:
First of all add the following "RegistryHelpers" class in your solution. I have added few methods in this class to get registrykey and value.

技术分享
using System;
using Microsoft.Win32;

namespace TestConsole
{
    public class RegistryHelpers
    {

        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);
        }
    }
}
View Code

 


Let‘s test this code with a console program to fetch the value of key:

技术分享
using System;

namespace TestConsole
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string keyPath = @"SOFTWARE\MyApp\Settings";
            string keyName = "MyAppConnectionStringKey";

            object connectionString = RegistryHelpers.GetRegistryValue(keyPath, keyName);

            Console.WriteLine(connectionString);
            Console.ReadLine();
        }
    }
}
View Code

 



Output:

技术分享

 

 
 

 

以上是关于注册表键值明明存在OpenSubKey始终返回null,解决方案的主要内容,如果未能解决你的问题,请参考以下文章

OpenSubKey() 注册表项的“绝对路径”?

在C#中列出ODBC数据源

如何用批处理语句获取reg命令的返回值?

在 c# 中,如何测试/获取/设置可能存在或不存在的注册表项?

powershell检测注册表键值判断

读取注册表