1

I am getting this error "use the 'new' keyword to create an object instance. (Object reference not set to an instance of an object.) " I checked similar questions on this forum but could not find a satisfactory answer. what I am trying to achieve is import string value of 1 into registry subkey HKEY_CURRENT_USER\Software\MyApp\TEST

What I noted during Debugging is that "regkey" appears to be set to Null at all the lines where it is used. I am setting

regkey = Registry.LocalMachine.OpenSubKey("HKEY_CURRENT_USER\Software\MyApp\TEST", True) 

, still not sure why its value is not picked up by program.

How do I implement New keyword to create an object instance ? I am using "Imports Microsoft.Win32" at the top level in program.

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles Button1.Click
   Dim regkey As RegistryKey
   regkey = Registry.LocalMachine.OpenSubKey("HKEY_CURRENT_USER\Software\MyApp\TEST", True)
   regkey.SetValue("TEST", "1", RegistryValueKind.String)
   regkey.close()
 End Sub
1
  • 1
    Well, you try to open a subkey of HKEY_CURRENT_USER with Registry.LocalMachine and I bet this gives back a null reference Commented Jul 14, 2014 at 13:52

1 Answer 1

2

You are trying to open HKEY_LOCAL_MACHINE\HKEY_CURENT_USER\Software\MyApp\TEST, which does not exist. Hence, RegistryKey.OpenSubKey returns null (Nothing).

You should

  1. fix your code (Registry.CurrentUser.OpenSubKey("Software\...") will probably do what you want), and
  2. add a null check (If regkey Is Nothing Then ...) between lines 2 and 3 that handles the problem gracefully.
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Heinzi, and Steve, thanks for showing me the mistake. I revised as per your instruction and the registry was imported..
Hi Heinzi, and Steve, thanks for showing me the mistake. I revised as per your instruction and the registry was imported.. [CODE] Dim regKey As RegistryKey regKey = Registry.CurrentUser.OpenSubKey("Software\Software\MyApp\TEST", True) regKey.SetValue("TEST", "1", RegistryValueKind.String) regKey.Close() [/CODE] Heinzi, Like you mentioned I will also add the null check just in case.
If Heinzi solved your issue, please mark the answer. It helps others finding similar solutions...among other things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.