Home > Software design >  Reading the installation date of the C# OS
Reading the installation date of the C# OS

Time:02-05

With the C# Core 3.1 WinForms application, the first installation date of the operating system cannot be read through regedit. It gives different results than the date given by "SystemInfo" command with CMD.

CMD "System Info":

CMD Image

Original Install Date: 11/26/2022, 1:08:26 PM

C# Read a "Regedit InstallDate(DWord)":

Regedit Image

Date: "1.01.1601 00:02:46"

C# Read a Date

RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, computerName);
key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false);
if (key != null)
{
    DateTime installDate =
        DateTime.FromFileTimeUtc(
            Convert.ToInt64(
                key.GetValue("InstallDate").ToString()));

    return installDate;
}
return DateTime.MinValue;

CodePudding user response:

The value in InstallDate is not a FILETIME value, but a Unix Time (seconds since 1970-01-01). You can use

var installDate = DateTimeOffset.FromUnixTimeSeconds(regValue);

to convert to a DateTimeOffset.

For other conversion methods see How do you convert epoch time in C#?

CodePudding user response:

@KlausGutter's answer is spot on, the value in the registry is a Unix time. If you want to convert it to a DateTime rather than a DateTimeOffset, then you could use something like

var installDate = DateTime.UnixEpoch.AddSeconds(regValue)

CodePudding user response:

You can use this method for Converting UnixTime or whatever it is :

public static DateTime FromDate(string SerialDate)
        {
            var year = Convert.ToInt32(SerialDate.Substring(0, 4));
            var mon = Convert.ToInt32(SerialDate[4].ToString()   SerialDate[5].ToString());
            var day = Convert.ToInt32(SerialDate[6].ToString()   SerialDate[7].ToString());
            try
            {
                var date = new DateTime(year, mon, day);
                return date;
            }
            catch(Exception ss)
            {
                return DateTime.Now;
            }
        }
  • Related