Search code examples
c#datewmi

C# can't take Windows InstallDate (f.e CIM_OperatingSystem)


I want to get Windows InstallDate from CIM_OperatingSystem. I've tried lots of variants but didn't succeed. I created DataTime massive but an error appeared. I succeeded once and the data was 11111111 or 01.01.0001. I would appreciate your help.

This is code:

DateTime WindowsInstallDate;

ManagementObjectSearcher windows = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM CIM_OperatingSystem");          

foreach (ManagementObject mo in windows.Get())
{
    WindowsInstallDate= DateTime.Parse(mo["InstallDate"].ToString());                          
}

label1.Text = WindowsInstallDate;

Thanks in advance. Waiting for your answer. I'm a beginner :(


Solution

  • Use the ManagementDateTimeConverter class in your code to convert WMI Dates to DateTime classes.

    WindowsInstallDate = ManagementDateTimeConverter.ToDateTime(mo["InstallDate"].ToString());
    

    It's worth noting this WMI class is pulling this data from the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion and the value for InstallDate. On Windows 10, this value gives you the install date of the most recent feature upgrade. There is a key called HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on <DATE>) that has the original OS InstallDate value.

    That key is variable as the <DATE> specified above is the date of the last upgrade. You will need to get the key name and the convert the registry data from unix (epoch) time to DateTime format, something like this would work. Excuse the crudeness of some of the code, more error handling can be added as needed. This is just a quick example.

    //Open Registry Key, search for subkey that starts with "Source OS" then open that key to get InstallDate data
    RegistryKey SetupKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\Setup");
    string SourceOSKeyName = SetupKey?.GetSubKeyNames().Where(x => x.StartsWith("Source OS")).FirstOrDefault();
            
    //Initialize new DateTime object with January 1st 1970 as its date (the start of unix time)
    DateTime InstallDate = new DateTime(1970, 1, 1);
    
    if (!string.IsNullOrEmpty(SourceOSKeyName))
    {
        int InstallDateValue = (int)SetupKey.OpenSubKey(SourceOSKeyName)?.GetValue("InstallDate");
        InstallDate = InstallDate.AddSeconds(InstallDateValue);
    }
    
    //If the key is not found the datetime value will be Jan 1st 1970.
    Console.WriteLine(InstallDate.ToString());