使用 C# 测试注册表中是否存在 DWORD 值
本文关键字:存在 DWORD 是否 测试 注册表 使用 | 更新日期: 2023-09-27 18:18:43
>我有一个Win Forms应用程序,该应用程序将PC移动到新的OU,然后将DWORD值写入注册表以指示移动是成功还是失败。其余操作完成后,它会重新启动PC。重新启动后,应用程序将重新启动自身并检查注册表值以了解哪些成功,哪些不成功,并在窗体上显示"检查"或"X"。
我想知道如何测试以查看 DWORD 值是否存在,然后读取它是否为"1"。我意识到我可以让自己变得容易,只是让应用程序编写一个字符串值,但我正在努力学习。
使用Visual Studio,当我尝试检查DWORD值是否为null时,我收到警告,我收到以下警告:表达式的结果始终为true,因为int类型的值永远不会等于int类型的null
好的,所以 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;
}
}
您可以使用可为空的int
做这样的事情 - 即 int?
-- 以及如果 reg 值不存在,则采用默认值的GetValue
重载:
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
更改检查顺序,以便在将object
转换为int
之前检查其为 null :
//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
查看它是否是null
检查后的int
。
另一种解决方案...
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;
}
}