C# 不能取 Windows InstallDate (f.e CIM_OperatingSystem)

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

我想从 CIM_OperatingSystem 获取 Windows InstallDate。我尝试了很多变体但没有成功。我创建了大量的 DataTime,但出现了错误。我成功了一次,数据是11111111或者01.01.0001。非常感谢您的帮助。

这是代码:

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;

提前致谢。等待你的答复。我是初学者:(

在您的代码中使用 ManagementDateTimeConverter class 将 WMI 日期转换为 DateTime classes。

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

值得注意的是,此 WMI class 正在从注册表项 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersionInstallDate 的值中提取此数据。在 Windows 10,此值为您提供最新功能升级的安装日期。有一个名为 HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on <DATE>) 的键具有原始 OS InstallDate 值。

该密钥是可变的,因为上面指定的 <DATE> 是上次升级的日期。您将需要获取密钥名称并将注册表数据从 unix(纪元)时间转换为 DateTime 格式,这样就可以了。请原谅某些代码的粗糙,可以根据需要添加更多错误处理。这只是一个简单的例子。

//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());