C # Reading decimal value from registry
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
a source to share
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 typestring
(like thisint
orbyte[]
) - value
string
but unparseddecimal
(""
,"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;
}
a source to share