Search code examples
c#registry

Reading a value from registry C#


I am trying to read the recent

this is the code i have right now:

RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Visual Studio\12.0\ProjectMRUList");
            string data2 = (string)registryKey.GetValue("File1".ToUpper());
            recentProjects.Items.Add(data2);

i keep getting a null error.

System.NullReferenceException: Object reference not set to an instance of an object.

The error is on

string data2 = (string)registryKey.GetValue("File1");

Solution

  • The subkey is actually "VisualStudio", not "Visual Studio". Try the below:

        RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VisualStudio\12.0\ProjectMRUList");
        string data2 = (string)registryKey.GetValue("File1".ToUpper());
    

    Or better still, you can have control over whether the environment is 32 or 64 bit, for example...

    using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64))
            {
                using (var key = hklm.OpenSubKey(@"Software\Microsoft\VisualStudio\12.0\ProjectMRUList"))
                {
                    string data2 = (string)key.GetValue("File1".ToUpper());
                }
            }