Share via


Getting error when reading a registry key: Object reference not set to an instance of an object

Question

Monday, February 25, 2013 6:41 PM

Hello,

I am trying to read and create a key, name and its value, but I am getting the following error.

The code verifies the existence of the key TabbedBrowsing and its name Enabled with the respective value 0.
If TabbedBrowsing does not exist create it.

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at UPI_IE8_GE_Settings.Program.Main(String[] args) in C:\Users\roserog\documents\visual studio 2010\Projects\UPI_IE8_GE_Settings\UPI_IE8_GE_Settings\Program.cs:line 140

Thanks for your help.

This is the code:

//TABS/DISABLE TABBED BROWSING
            Console.WriteLine("");
            RegistryKey subkey3 = key.OpenSubKey("Software\\Microsoft\\Internet Explorer", true);
            RegistryKey subkey3a = key.OpenSubKey("Software\\Microsoft\\Internet Explorer\\TabbedBrowsing", true);
            string[] names3 = subkey3.GetSubKeyNames();
            string[] names3a = subkey3a.GetValueNames();
            string YesTabbedBrowsingKeyExists = "";
            string NoTabbedBrowsingKeyExists = "";
            string YesEnabledNameExists = "";
            string NoEnabledNameExists = "";

            if (subkey3a == null)
            {
                Console.WriteLine("WOW, YOU ARE EMPTY");
                System.Threading.Thread.Sleep(10000);
                return;
            }
            foreach (string keyname in names3)
            {
                if (keyname.Equals("TabbedBrowsing", StringComparison.CurrentCulture))
                {
                    // Found TabbedBrosing
                    YesTabbedBrowsingKeyExists = "1";
                    break;
                }
                else
                {
                    // No Found TabbedBrowsing
                    NoTabbedBrowsingKeyExists = "1";
                }
            }
            if (YesTabbedBrowsingKeyExists == "1")
            {
                Console.WriteLine("YES Found TabbedBrowsing");
                foreach (string name in names3a)
                {
                    if (name.Equals("Enabled", StringComparison.CurrentCulture))
                    {
                        // Found TabbedBrowsing Enabled
                        YesEnabledNameExists = "1";
                        break;
                    }
                    else
                    {
                        // No Found TabbedBrowsing Enabled
                        NoEnabledNameExists = "1";
                    }
                }
                if (YesEnabledNameExists == "0")
                {
                    Console.WriteLine("Found TabbedBrowsing and Enabled");
                    int myValue3a = (int)subkey3a.GetValue("Enabled");
                    if (myValue3a == 0)
                    {
                        Console.WriteLine("Recommended TABBED BROWSING value: {0} Unchecked Tabbed Browsing", myValue3a);
                    }
                    else
                    {
                        Console.WriteLine("Setting the right GE Recommendation");
                        subkey3a.SetValue("Enabled", "0", RegistryValueKind.DWord);
                    }
                }
                if (NoEnabledNameExists == "1")
                {
                    Console.WriteLine("NO Found Enabled, creating it ");
                    Console.WriteLine("Setting the right GE Recommendation");
                    subkey3a.SetValue("Enabled", "0", RegistryValueKind.DWord);
                }
            }
            if (NoTabbedBrowsingKeyExists == "1")
            {
                Console.WriteLine("NO Found TabbedBrowsing, creating it ");
                Console.WriteLine("Setting the right GE Recommendation");
                subkey3.CreateSubKey("TabbedBrowsing");
                subkey3a.SetValue("Enabled", "0", RegistryValueKind.DWord);
            }

         

All replies (4)

Monday, February 25, 2013 8:19 PM ✅Answered | 1 vote

Your code isn't going to work correctly.  Firstly we'll assume that 'key' is not null.  If it is then the first line will crash.  If you get past that then the GetSubkeyNames methods will fail if the keys you retrieved don't exist.  You check for null a little further down but by then it is too late.  The remainder of the code seems relatively safe once you properly detect the null subkeys.

I think you're doing more work then you need to.  Don't bother enumerating the subkeys of a key if you exactly which key you want.  Just try to open the key for reading.  If you get null back then the key didn't exist.  If the key does exist then you can request a specific value.  Again, if you get null back the value doesn't exist.

Another area you need to be real careful with is read/write permissions.  If you are only going to read a key or value then you should only request read access.  Starting with Vista Windows will do registry virtualization on apps that aren't Vista aware.  What this basically means to you is that if you request read access then the key will exist or it won't.  In the specific code you have this will be under HKLM.  But if you request write access then Windows throws up an access denied error (because users don't have write privileges).  Registry virtualization kicks in (again unless your app is Vista aware) and redirects your request to a subkey that you do have write permissions to.  This is to allow older apps to behave correctly.  But the result of this is that you can get mixed results if you query for the existence of a key first (which gets HKLM) but then try to open it for write (which gets redirected).  In your case you are only reading so request only read access.

Michael Taylor - 2/25/2013
http://msmvps.com/blogs/p3net


Monday, February 25, 2013 10:35 PM ✅Answered

I believe tabbed browsing is a per-user setting (ignoring network policies) so the following should work:

bool tabbedBrowsing = false;
var keyName = @"Software\Microsoft\Internet Explorer\TabbedBrowsing";

using (var key = Registry.CurrentUser.OpenSubKey(keyName))
{
   if (key != null)
   {
      var value = key.GetValue("Enabled", 0);                    
      tabbedBrowsing = (value != null) ? (Convert.ToInt32(value) != 0) : false;
   };
};

if (!tabbedBrowsing)
{
   using (var key = Registry.CurrentUser.CreateSubKey(keyName))
   {
      key.SetValue("Enabled", 1);
   };
};

Personally whenever I have to write registry code I create extension methods to simplify my code. You could create one to get a boolean value given a key and value. Another one might be to get a value given the key path and value so that you could eliminate the need for the using statement.

Michael Taylor - 2/25/2013
http://msmvps.com/blogs/p3net


Monday, February 25, 2013 8:35 PM

Mike,

Thank you very much for your explanation. And yes, you are right about reading,writing into the registry. But, my goal of this project is to create a Console Application that changes IE settings in the registry and launches IE9. I did it on vbscript and want to do it on C#.

I am enumerating the key paths to make sure I am changing a specific registry path. I do not want to screw it up. Just being cautious with the registry.

And you are right about the null value also, I was getting that error because a variable was already null when reading the reg path.

Can you guys still help me with my logic and go through it?. I a stuck in something else. I am still learning C#


Monday, February 25, 2013 8:37 PM

By the way, can i run that console in the background once the whole executable has the 100% release version ? My manager does not like the DOS background window. :(