I'm trying to retrieve de int value of this reg dword: SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\InstallDate
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.
I'm starting with this:
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;
}
}
Any suggestions?
The issue you have is an issue between the 32 bit registry view and the 64 bit registry view as described on MSDN here .
To solve it you can do the following. Note that the returned value is a Unix timestamp (ie 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);
}
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
.
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")));
It isn´t to hard to solve. First of all - skip HKLM if using 64bit. (LocalMachine) Use HKCU (CurrentUser) Use a stringvalue instead of dword for a Installdate. Get stringvalue from registry and then "parse" to DateTime.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.