获得十进制值从注册表中的DWORD [英] Get decimal value from a DWORD in the registry

查看:285
本文介绍了获得十进制值从注册表中的DWORD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检索该寄存器DWORD的德int值: SOFTWARE \微软\的Windows NT \ CURRENTVERSION \ InstallDate

I'm trying to retrieve de int value of this reg dword: SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate

我能够检索一个字符串的价值,但我不能让DWORD的int值... 最后,我想有窗户的安装日期。 我搜索了找到了一些解决方案,但没有奏效。

I'm able to retrieve a strings' value, but i cant get the int value of the dword... At the end, i would like to have the install date of windows. I searched an found some solutions, but none worked.

我开始有这样的:

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;
    }
}

有什么建议?

推荐答案

你的问题是,32位注册表视图和64位注册表视图MSDN的这里

The issue you have is an issue between the 32 bit registry view and the 64 bit registry view as described on MSDN here.

要解决这个问题,你可以做到以下几点。注意,返回的值是一个Unix时间戳(即秒,从1970年1月1日的数字),所以你需要操作的结果,以获得正确的日期:

To solve it you can do the following. Note that the returned value is a Unix timestamp (i.e. the number of seconds from 1 Jan 1970) so you need to manipulate the result to get the correct date:

//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 返回的是一个对象,但 AddSeconds 需要一个数值,所以我们需要转换的结果。我可以使用 UINT 上面这是足够大的存储的 DWORD 这就是(32位),但我去与的Int64

The return from GetValue is an Object but AddSeconds requires a numeric value so we need to cast the result. I could have used uint above as that's big enough to store the DWORD which is (32 bits) but I went with Int64.

如果您preFER它更简洁,你可以在一个大线改写空检查里面的一部分:

If you prefer it more terse you could rewrite the part inside the null check in one big line:

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

这篇关于获得十进制值从注册表中的DWORD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆