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

Nom*_*ake 1 .net c#

我正在尝试检索此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;
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

pet*_*ids 6

你的问题是,32位注册表视图和MSDN上描述的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);
}
Run Code Online (Sandbox Code Playgroud)

返回GetValue是一个ObjectAddSeconds需要一个数值,所以我们需要转换结果.我可以用uint上面那个足够大的存储DWORD(32位),但我去了Int64.

如果您更喜欢它更简洁,您可以在一个大行中重写null检查中的部分:

DateTime installDate = new DateTime(1970, 1, 1)
                      .AddSeconds(Convert.ToUInt32(key.GetValue("InstallDate")));
Run Code Online (Sandbox Code Playgroud)