Checking if registry key exists?

N1c0_ds

Active Member
Licensed User
I want to save my application settings to the registry. I want to check if keys exist and create a key if they don't.

It's easy to do it for one key only with errorlabel:
B4X:
Sub Loadsettings
ErrorLabel(KeyNotFound)
TxtServerPath.Text=Registry.GetValue(Regpath,"ServerURL")
Return
KeyNotFound:
 Registry.CreateSubKey("",Regpath)
 Registry.SetStringValue(Regpath,"ServerURL","http://ayvegh.com/~nico/")
End Sub
But if there is more than one entry (it's for the whole skin + all the settings), it makes much less safe. Let's say only 1 of the entries is missing. Using this method, we would have to rewrite every registry entry to the default value, thus erasing the user's settings.

Is there a "FileExist" for the registry keys?
 

Mr_Gee

Active Member
Licensed User
What if you made a 2nd sub which checks this for you?

B4X:
Sub Global
      key = "Software\My Application"
End Sub 

Sub Loadsettings

    CheckReg("ServerURL","http://ayvegh.com/~nico/")
End Sub

Sub CheckReg(What,Value)
  reg.New1
  reg.RootKey(reg.rtCurrentUser)
  ErrorLabel(NotCreatedYet)
  msgbox("The value is: " & reg.GetValue(key,What))
  return
NotCreatedYet: 'creates the subkey if it didn't exist
  reg.CreateSubKey(Value,key&"\"&What)
  msgbox("The key was created.")    
End Sub
BTW you might want to check the code, I'm not sure if
reg.CreateSubKey(Value,key&"\"&What)
is the correct way
 

N1c0_ds

Active Member
Licensed User
That wouldn't work because errorlabel ends the sub. That's why Loadsettings is the last thing I do in App_start
 
Top