註冊表鍵值明明存在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.ide

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:fetch

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:

this

相關文章
相關標籤/搜索