Tony Moriaci
Tony Moriaci

Reputation:

C# Reading Decimal Value From Registry

i have a NumericUpDown control and want to update its contents from the registry. So far this is what i got:

this.apTime.Value = APRegsitry.GetValue("apTime").ToString();

Obviously that wont work so how do i set this.apTime to the value of the registry key?

Upvotes: 0

Views: 1737

Answers (2)

Lucas
Lucas

Reputation: 17434

You shouldn't trust the value from the registry since a user can edit it outside your application. You need to handle the following cases:

  • registry key doesn't exist
  • registry key exists, but name/value doesn't exist (null)
  • you expect a string, value is not string type (e.g. it is an int or byte[])
  • value is a string but not parsable to decimal ("", "abc")

If the key doesn't exist, RegistryKey.OpenSubKey(name) returns null. You might want to handle that and create the key. If the key exists, but not the name/value pair, then RegistryKey.GetValue(name) returns null. You can handle that by passing a default value to the overload RegistryKey.GetValue(name, defaultValue) or by using ??.

Now, if the name/value pair exists but has an invalid value ("", "abc"), you'll get an exception from Parse(). The Parse() methods (in int, decimal, DateTime, etc) have been pretty much been deprecated by TryParse(). They return false instead of throwing FormatException.

// passing the default value to GetValue()
object regValue = APRegistry.GetValue("apTime", "0");
// ...same as...
object regValue = APRegistry.GetValue("apTime") ?? "0";

decimal value;

// regValue will never be null here, so safe to use ToString()
if(decimal.TryParse(regValue.ToString(), out value))
{
    this.apTime.Value = value;
}
else
{
    // Name/pair does not exist, is empty,
    // or has invalid value (can't parse as decimal).

    // Handle this case, possibly setting a default value like this:
    this.apTime.Value = 0; 
}

Upvotes: 1

JaredPar
JaredPar

Reputation: 755161

I'm not entirely sure what the issue is. Are you having problems converting it to a decimal? If so try Decimal.Parse

Object obj = APRegistry.GetValue("apTime");
String str = obj != null ? obj.ToString() : "0";
Decimal value = Decimal.Parse(str);
this.apTime.Value = value;

If not can you elaborate further as to what the problem is?

EDIT Updated code to account for null return from GetValue

Upvotes: 1

Related Questions