我正在尝试检索此 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/