使用 C# 测试注册表中是否存在 DWORD 值

Test if DWORD value exists in registry using C#

我有一个 Win Forms 应用程序,除其他外,它会将 PC 移动到新的 OU,然后将 DWORD 值写入注册表以指示移动是成功还是失败。它会在其余操作完成后重新启动 PC。重新启动后,应用程序会自行重新启动并检查注册表值以了解成功与否,并在表单上显示 'checks' 或“X”。

我想知道如何测试 DWORD 值是否存在,然后读取它是否为“1”。我意识到我可以自己轻松实现这一点,让应用程序写入一个字符串值,但我正在努力学习。

使用 Visual Studio 当我尝试检查 DWORD 值是否为空时收到警告 我收到以下警告: 表达式的结果始终为真,因为类型的值int 永远不等于 int

类型的 null

好的,所以 int 值不能为 null,那么我还能如何测试它是否存在于注册表中以避免异常?请参阅下面的代码。

RegistryKey domainJoin = Registry.LocalMachine.OpenSubKey
                   (@"SOFTWARE\SHIELDING", 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;
                    }
                }

您可以使用可为 null 的 int(即 int?)和 GetValue 重载来执行类似的操作,如果 reg 值不存在则采用默认值:

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.TryParsenull检查之后看看它是否是一个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;
    }
}