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
  • 20,323
  • 43
  • 37
  • 57
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
  • 16,053
  • 9
  • 49
  • 91
  • 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
  • 370
  • 1
  • 3
  • 16