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

标签 c# .net

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

我能够检索字符串的值,但无法获取双字的 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;
    }
}

有什么建议吗?

最佳答案

您遇到的问题是 32 位注册 TableView 和 64 位注册 TableView 之间的问题,如 MSDN here 中所述.

要解决它,您可以执行以下操作。请注意,返回值是一个 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")));

关于c# - 从注册表中的 DWORD 中获取十进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25912947/

相关文章:

c# - 使用 MongoDB C# 映射私有(private)支持字段

c# - 格式化 double 值,如货币但不带货币符号 (C#)

.net - 将 Dapper 添加到企业库?

c# - 琐事多于真正重要 : Why no new() constraint on Activator. CreateInstance<T>()?

c# - 如何确定三角形是否包含特定点?

c# - 将枚举传递给强类型部分 View

c# - WCF 客户端字段正在丢失值

c# - 并行扩展

.net - 我们可以在.Net 中针对 Oracle 19c 使用 System.Data.OracleClient 吗?

.net - 使用 CCKeyDerivationPBKDF 获取派生 key