Search code examples
c#registry

c# preventing missing registry key from crashing my app


I have an app that is set to read the status of the writeprotect value in the storage device policies subkey. Normally, this subkey is present on most windows computers, but I just noticed that after a fresh windows install it is not present on mine and it crashed the app when I ran it.

This is how I have it laid out.

        public MainWindow()
    {
        InitializeComponent();

        int key = (int)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies", "WriteProtect", -1);
        if (key == -1)
        {
            ProtectStatus.Foreground = Brushes.Red;
            ProtectStatus.Text = "No Value Found. Turn On";
        }

        if (key == 0)
        {
            ProtectStatus.Foreground = Brushes.Red;
            ProtectStatus.Text = "Write Protection is Off";
        }
        else
        {
            ProtectStatus.Foreground = Brushes.LawnGreen;
            ProtectStatus.Text = "Write Protection is On";   
        }
    }

The code works fine if the StorageDevicePolicies subkey actually exists, but is there a way to stop it from crashing my app if it doesnt?

The error is:System.NullReferenceException: 'Object reference not set to an instance of an object.'


Solution

  • The documentation indicates:

    Retrieves the value associated with the specified name, in the specified registry key. If the name is not found in the specified key, returns a default value that you provide, or null if the specified key does not exist.

    So you just need to add a null check to your code:

    var value = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies", "WriteProtect", -1);
    
    int key = value == null ? -1 : (int)value;