0

Code:

try 
{
     RegistryKey SQMRegKey = Registry.LocalMachine.OpenSubKey("CurrentControlSet\\Control\\WMI\\Autologger", true);
     //SQMRegKey.DeleteSubKey("SQMLogger");
     SQMRegKey.DeleteSubKeyTree("SQMLogger");
     SQMRegKey.Close();
} 
catch (Exception ex)
{
     MessageBox.Show(this, ex.ToString());
}

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

pfx
  • 15,218
  • 41
  • 36
  • 52
wolfen
  • 13
  • 3
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – D-Shih Oct 05 '18 at 11:15

2 Answers2

0

OpenSubKey may fail, in which case the return value is null. You use the reference, i.e. SQMRegKey without checking if it actually points to a valid object.

try 
{
     var SQMRegKey = Registry.LocalMachine.OpenSubKey("CurrentControlSet\\Control\\WMI\\Autologger", true);
     if(SQMRegKey != null)
     {
        SQMRegKey.DeleteSubKeyTree("SQMLogger");
        SQMRegKey.Close();
     }
} 
catch (Exception ex)
{
     MessageBox.Show(this, ex.ToString());
}
Marius Bancila
  • 15,632
  • 8
  • 47
  • 86
  • I take note of the reference to the null value and will look to using != or GetValue method – wolfen Oct 05 '18 at 13:18
0

The registry path is not correct. Please use the below modified code:

        try
        {
            RegistryKey SQMRegKey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\WMI\\Autologger", true);
            //SQMRegKey.DeleteSubKey("SQMLogger");

            SQMRegKey.DeleteSubKeyTree("SQMLogger");

            SQMRegKey.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
A. Gopal Reddy
  • 310
  • 3
  • 15