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 not working like this, how do I set this.apTime to the value of a registry key?

0


a source to share


2 answers


I'm not really sure what the problem is. Are you having trouble converting it to 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 you can't clarify yet, what is the problem?

EDIT Updated code for account null return from GetValue

+1


a source


You should not trust the value from the registry, as the user can edit it outside of your application. You need to handle the following cases:

  • Registry key does not exist
  • registry key exists but name / value does not exist ( null

    )
  • you expect that the string

    value is not a type string

    (like this int

    or byte[]

    )
  • value string

    but unparsed decimal

    ( ""

    , "abc"

    )

RegistryKey.OpenSubKey(name)

Returns null if the key does not exist . You might want to handle this and generate a key. If the key exists but not a name / value pair, then it RegistryKey.GetValue(name)

returns null. You can handle this by passing a default overload RegistryKey.GetValue(name, defaultValue)

or using ??

.



Now if a name / value pair exists but has an invalid value ( ""

, "abc"

), you will get an exception from Parse()

. Methods Parse()

(a int

, decimal

, DateTime

etc.) have been largely obsolete 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; 
}

      

+1


a source







All Articles