[英]C# Reading Decimal Value From Registry
i have a NumericUpDown control and want to update its contents from the registry. 我有一个NumericUpDown控件,想从注册表中更新其内容。 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? 显然,这行不通,所以我如何将this.apTime设置为注册表项的值?
I'm not entirely sure what the issue is. 我不确定是什么问题。 Are you having problems converting it to a decimal? 您在将其转换为小数时遇到问题吗? If so try Decimal.Parse 如果是这样,请尝试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 编辑更新的代码以说明从GetValue返回空值
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: 您需要处理以下情况:
null
) 注册表项存在,但名称/值不存在( null
) string
, value is not string
type (eg it is an int
or byte[]
) 您期望一个string
,值不是string
类型(例如,它是int
或byte[]
) string
but not parsable to decimal
( ""
, "abc"
) value是一个string
但不能解析为decimal
( ""
, "abc"
) If the key doesn't exist, RegistryKey.OpenSubKey(name)
returns null. 如果键不存在,则RegistryKey.OpenSubKey(name)
返回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. 如果键存在,但名称/值对不存在,则RegistryKey.GetValue(name)
返回null。 You can handle that by passing a default value to the overload RegistryKey.GetValue(name, defaultValue)
or by using ??
您可以通过将默认值传递给重载RegistryKey.GetValue(name, defaultValue)
或使用??
. 。
Now, if the name/value pair exists but has an invalid value ( ""
, "abc"
), you'll get an exception from Parse()
. 现在,如果名称/值对存在但具有无效值( ""
, "abc"
),您将从Parse()
获得异常。 The Parse()
methods (in int
, decimal
, DateTime
, etc) have been pretty much been deprecated by TryParse()
. TryParse()
已不推荐使用Parse()
方法( int
, decimal
, DateTime
等TryParse()
。 They return false
instead of throwing FormatException
. 他们返回false
而不是抛出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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.