从注册表中的DWORD中获取十进制值

本文关键字:十进制 获取 注册表 DWORD | 更新日期: 2023-09-27 18:22:47

我正在尝试检索此reg dword的de int值:SOFTWARE''Microsoft''Windows NT''CurrentVersion''InstallDate

我可以检索字符串的值,但无法获取dword的int值。。。最后,我想知道windows的安装日期。我搜索并找到了一些解决方案,但都不起作用。

我从这个开始:

public void setWindowsInstallDate()
{
    RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE'Microsoft'Windows'NT'CurrentVersion");
    if (key != null)
    {
        object value = key.GetValue("InstallDate");
        // some extra code ??? ...
        WindowsInstallDate = value;
    }
}

有什么建议吗?

从注册表中的DWORD中获取十进制值

您遇到的问题是MSDN上描述的32位注册表视图和64位注册表视图之间的问题。

要解决此问题,您可以执行以下操作。请注意,返回的值是Unix时间戳(即1970年1月1日起的秒数),因此您需要处理结果以获得正确的日期:

//get the 64-bit view first
RegistryKey key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
key = key.OpenSubKey(@"SOFTWARE'Microsoft'Windows NT'CurrentVersion");
if (key == null)
{
    //we couldn't find the value in the 64-bit view so grab the 32-bit view
    key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
    key = key.OpenSubKey(@"SOFTWARE'Microsoft'Windows NT'CurrentVersion");
}
if (key != null)
{
    Int64 value = Convert.ToInt64(key.GetValue("InstallDate").ToString());
    DateTime epoch = new DateTime(1970, 1, 1);
    DateTime installDate = epoch.AddSeconds(value);
}

GetValue的返回是Object,但AddSeconds需要一个数值,因此我们需要强制转换结果。我本可以使用上面的uint,因为它足够大,可以存储DWORD(32位),但我选择了Int64

如果你喜欢它更简洁,你可以用一大行重写空检查中的部分:

DateTime installDate = new DateTime(1970, 1, 1)
                      .AddSeconds(Convert.ToUInt32(key.GetValue("InstallDate")));

这并不难解决。首先-如果使用64位,请跳过HKLM。(LocalMachine)使用HKCU(CurrentUser)对于Installdate,请使用字符串值而不是双字。从注册表中获取字符串值,然后"解析"到DateTime。