sp_m
sp_m

Reputation: 2707

Read value of registry in c#

I have c# application which include code to retrieve registry values and check it's values.registry values stored in following manner:

MainKey:

Name:user123
Isregistered:no

however if Isregistered returns "no",it will display appropriate message.
i am getting error like this

Object reference not set to an instance of an object.

C# Code:

RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"HKEY_CURRENT_USER\\MainKey", true);
string currentKey;
currentKey = reg.GetValue("Isregistered", true).ToString();
if (currentKey == "yes")
{
  Console.WriteLine("availble");
}
else
{
  Console.WriteLine("Not availble");
}


i am getting error on
"currentKey = reg.GetValue("Isregistered", true).ToString();"

Upvotes: 1

Views: 8420

Answers (3)

AksharRoop
AksharRoop

Reputation: 2293

I see two problems in your code:

1)

// You're searching for HKEY_CURRENT_USER in HKEY_LOCAL_MACHINE
// Use Registry.CurrentUser instead.
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"HKEY_CURRENT_USER\\MainKey", true);
string currentKey;
currentKey = reg.GetValue("Isregistered", true).ToString();

Find more about CurrentUser field here

2) The other aspect is that either use @ or \\ not both in the registry path. i.e.

OpenSubKey(@"HKEY_CURRENT_USER\MainKey", true);

or

OpenSubKey("HKEY_CURRENT_USER\\MainKey", true);

Find more about verbatim string literals here

Upvotes: 3

Petr Behenský
Petr Behenský

Reputation: 620

You are trying to open HKEY_CURRENT_USER using LocalMachine registry. Use Registry.CurrentUser.OpenSubKey(@"MainKey", true) instead.

Upvotes: 0

WillEllis
WillEllis

Reputation: 489

You've used @ and escaped the backslash. Also you'll want to ensue current key isn't null.

See the GetValue call here: http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.getvalue.aspx

Good luck!

Upvotes: 2

Related Questions