It can happen if you are on a 64-bit machine. Create a helper class first (requires .NET 4.0 or later):
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);
}
}
Usage:
string keyPath = @"SOFTWAREMyAppSettings";
string keyName = "MyAppConnectionStringKey";
object connectionString = RegistryHelpers.GetRegistryValue(keyPath, keyName);
Console.WriteLine(connectionString);
Console.ReadLine();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…