首页 > 解决方案 > 如何从注册表中读取 REG_DWORD 类型的大值?

问题描述

我有以下方法:

public static object GetRegValue(RegistryHive hive, string subKey, string key)
{
    try
    {
        var view32 = RegistryKey.OpenBaseKey(hive,
                                RegistryView.Default);
        using (var regKey = view32.OpenSubKey(subKey, false))
        {
            return regKey.GetValue(key, 0);
        }
    }
    catch (Exception)
    {
        Logger.Log($"Get {subKey} + {key} from Registry failed");
        return 0;
    }
}

每当我需要访问某个注册表路径时,我都会使用它。但是,我在访问 0xa8200410 (2820670480) 时在以下代码段中发现了一个错误

Convert.ToUInt64(GetRegValue(RegistryHive.CurrentUser, RegistryPath, RegistryKeyName));

我从中看到了GetValue()价值Int32。它给了我一些很大的负值。所以我搜索了将其转换为ulong.

var value = 0ul;
unchecked
{
    value = (ulong)(int)Misc.GetRegValue(RegistryHive.CurrentUser, RegistryPath, RegistryKeyName);
}

尽管如此,它给了我错误的价值。

谁能给我一个关于在 C# 中从注册表中获取大 DWORD 值的想法?

标签: c#registry

解决方案


2820670480 值是一个无符号整数。当它被转换为int时,你会得到一个负值。因此,您需要将其转换为uint. 但是,该方法返回一个基础类型为GetValue()的装箱值。如果您尝试将其直接转换为 a ,它将不起作用:intuint

// This will throw an InvalidCastException
int value = (uint)GetRegValue(RegistryHive.CurrentUser, RegistryPath, RegistryKeyName);

您需要先将其拆箱(通过将其int转换为 a ),然后将其转换为 a uint

int temp = (int)GetRegValue(RegistryHive.CurrentUser, 
                            RegistryPath, RegistryKeyName); //-1474296816
int value = (uint)temp; // 2820670480

或者你仍然可以在一个语句中做到这一点:

int value = (uint)(int)GetRegValue(RegistryHive.CurrentUser, 
                                   RegistryPath, RegistryKeyName);

然后,您可以将其转换为ulong(AKA, UInt64) 但这不是必需的。无论如何,DWORD 的值不能大于 32 位。


推荐阅读