我有一个Win Forms应用程序,其中包括将PC移动到新OU,然后将DWORD值写入注册表以指示移动是成功还是失败。在其余操作完成后,它会重新启动PC。重启后,应用程序重新启动并检查注册表值是否成功,什么不成功,并在表单上显示“检查”或“X”。
我想知道如何测试DWORD值是否存在,然后读取它是否为“1”。我意识到我可以让自己变得容易,只是让应用程序写一个字符串值,但我正在努力学习。
使用Visual Studio我在尝试检查DWORD值是否为null时收到警告我收到以下警告:表达式的结果始终为true,因为int类型的值永远不等于null输入int
好的,所以int值不能为null,那么我怎么测试它是否存在于注册表中以避免异常?请参阅下面的代码。
RegistryKey domainJoin = Registry.LocalMachine.OpenSubKey
(@"SOFTWARE\SHIELDING\5", RegistryKeyPermissionCheck.ReadWriteSubTree);
//If the domain join was attempted, check outcome...
if (domainJoin != null)
{
//Check if move to OU was successful
int ouMoveVal = (int)domainJoin.GetValue("movePC");
if (ouMoveVal != null) <-----HERE IS WHERE I GET THE WARNING
{
//If PC move to new OU was successful
//show 'check' mark
if (ouMoveVal == 1)
{
picChkOU.Visible = true;
}
//If PC move to new OU was NOT successful
//show 'X' mark
else
{
picXOU.Visible = true;
}
}
答案 0 :(得分:2)
如果reg值不存在,您可以使用可为空的int
- 即int?
- 以及GetValue
重载来执行此类操作:< / p>
int? ouMoveVal = (int?) domainJoin.GetValue("movePC", new int?());
if (ouMoveVal.HasValue)
有关可空的更多内容:https://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
答案 1 :(得分:1)
更改检查的顺序,以便在将object
转换为int
之前检查//Check if move to OU was successful
object ouMoveVal = domainJoin.GetValue("movePC");
if (ouMoveVal != null)
{
// try to convert to int here and continue...
:
null
这意味着您可以从返回的Int32.TryParse
对象提供的信息中受益,表明密钥不存在。
然后您可以int
查看null
检查后IntPtr.Zero
是否为IntPtr
。
答案 2 :(得分:0)
另一种解决方案......
using Microsoft.Win32;
private static int ReadRegistryIntValue(string sSubKey, string sKeyName)
{
try
{
int retValue = 0;
RegistryKey rkSearchFor = Registry.LocalMachine.OpenSubKey(sSubKey);
if (rkSearchFor == null)
{
return retValue;
}
else
{
try
{
retValue = Convert.ToInt32(rkSearchFor.GetValue(sKeyName));
}
catch (Exception)
{
return 0;
}
finally
{
rkSearchFor.Close();
rkSearchFor.Dispose();
}
}
return retValue;
}
catch (Exception)
{
return 0;
}
}