簡體   English   中英

從注冊表中的DWORD獲取十進制值

[英]Get decimal value from a DWORD in the registry

我正在嘗試檢索此注冊表字的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;
    }
}

有什么建議么?

您遇到的問題是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

如果您更喜歡它,則可以在大行中重寫null檢查中的部分:

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

這並不難解決。 首先-如果使用64位,請跳過HKLM。 (LocalMachine)使用HKCU(CurrentUser)對於安裝日期,請使用字符串值而不是dword。 從注冊表中獲取字符串值,然后“解析”到DateTime。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM