I would like to read name and value pairs from Windows registry. I want to use a static class for it. The static class contains methods, what reads name/value pairs from Win Registry database and fill they into a Dictionary. I want to use this static method from my console application but I got a System.Null ReferenceExeption: 'Object reference not set to an instance of an object.' The codes:
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Win32;
namespace Winx64RegistryManipulator
{
public enum RegistryAg
{
HKLM, //= HKEY_LOCAL_MACHINE
HCU //= HKEY_CURRENT_USER
}
public static class RegManipulator
{
#region Variables
static RegistryAg regAg;
static string path;
static Dictionary<string, string> keyPairs; //this will contains the name/value pairs
#endregion
#region Constructors
//Static class - no constuctor
#endregion
#region Public methods and functions
public static Dictionary<string, string> ReadRegKeys(RegistryAg ag, string path)
{
RegistryKey key;
if (ag == RegistryAg.HKLM) //HKEY_LOCAL_MACHINE
{
key = Registry.LocalMachine.OpenSubKey(path); //Open the Registry tree
foreach (var item in key.GetValueNames())
{
RegistryValueKind rkv = key.GetValueKind(item);
if (rkv == RegistryValueKind.Binary)
{
var value = (byte[])key.GetValue(item);
keyPairs.Add(item.ToString(), BitConverter.ToString(value));
}
else if (rkv == RegistryValueKind.DWord || rkv == RegistryValueKind.QWord)
{
var value = int.Parse(key.GetValue(item));
keyPairs.Add(item.ToString(), value.ToString());
}
else
{
keyPairs.Add(item.ToString(), key.GetValue(item).ToString());
}
}
return keyPairs;
}
else
{
//more code
return keyPairs;
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Winx64RegistryManipulator;
namespace Teszt
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
keyValuePairs = RegManipulator.ReadRegKeys(RegistryAg.HKLM, "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Test");
Console.ReadKey();
}
}
}