Writing (and reading) boolean data to the registry

  • Thread starter Thread starter Bry
  • Start date Start date
B

Bry

I'm having problems writing (and reading) boolean data to the registry.

// Write a boolean value to the registry
// I've not included the obvious bits of code in these samples
bool myBool = true;
myRegistryKey.SetValue("SomeValue", myBool);

This gives me a registry value with string data containing "True"

// Read my boolean data back from the registry
bool myBool;
myRegistryKey.GetValue("SomeValue");

This produces a run time error, "InvalidCastException" was unhandled

I understand why I'm getting the exception, but I'm not sure what I
need to do to achieve what I'm trying to do. Can anyone point out what
I'm missing?

Thanks.
 
Hi Bry,

First, I don't see why the code you posted would throw an exception:

bool myBool;
myRegistryKey.GetValue("SomeValue");

This code would not actually *do* anything. You are not assigning the return
value of the function to anything. In fact, the RegistryKey.GetValue()
method is not documented as throwing an InvalidCastException at all.

Now, I can see how the *following* code would throw an InvalidCastException:

bool MyBool = myRegistryKey.GetValue("SomeValue");

The RegistryKey.GetValue() method returns a type of object, not boolean. You
would have to cast it as boolean.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
A watched clock never boils.
 
D'oh! I've posted the code incorrectly. Thanks for pointing that out.

It should read

// Read my boolean data back from the registry
bool myBool;
myBool = (bool) myRegistryKey.GetValue("SomeValue");

The last line is the one that throws the InvalidCastException
 
Bry said:
// Read my boolean data back from the registry
bool myBool;
myBool = (bool) myRegistryKey.GetValue("SomeValue");

I think you need to use Convert.ToBool, rather than trying to *cast*
to a bool, because your "True" or "False" is presumably stored in the
Registry as a string literal.

P.
 
You can store both string and binary data in the Registry. If you input
binary data (boolean), you will get back binary data.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
A watched clock never boils.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top