I'm returning a value from Win32_OperatingSystem
using System.Management
(I know about Microsoft.Management.Infrastructure
but I'm just doing some testing).
This is what I run:
string bootTime = "";
//Creating a management searcher object
ManagementObjectSearcher mgmtObjSearcher = new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem");
//Collection to hold "results"
ManagementObjectCollection objCollection = mgmtObjSearcher.Get();
foreach (ManagementObject mgmtObject in objCollection)
{
bootTime = mgmtObject["LastBootUpTime"].ToString();
}
But when trying to run Convert.ToDateTime(bootTime).ToString("dd/MM/yyyy hh:mm:ss");
I get the following error:
System.FormatException: 'String was not recognized as a valid DateTime.'
It looks like the LastBootUpTime value is being returned as 20190703085750.500000+060
which I can't seem to convert using Convert.ToDateTime
and can't work with using DateTime.Parse
Can someone lend a helping hand and let me know where I'm going wrong? I just want to return the LastBootUpTime and convert a specific string format ("dd/MM/yyyy hh:mm:ss"). Any help is very much appreciated :)
Following from Ňɏssa Pøngjǣrdenlarp's and Soner Gönül's comments, this is what I ended up with:
string bootTime = "";
//Creating a management searcher object
ManagementObjectSearcher mgmtObjSearcher = new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem");
//Collection to hold "results"
ManagementObjectCollection objCollection = mgmtObjSearcher.Get();
foreach (ManagementObject mgmtObject in objCollection)
{
bootTime = ManagementDateTimeConverter.ToDateTime(mgmtObject["LastBootUpTime"].ToString()).ToString("dd/MM/yyyy HH:mm:ss");
}
UPDATE
Following infinit_e comment, this is how I would get the value without using a foreach
loop:
string bootTime = new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem").Get()
.OfType<ManagementObject>()
.First()
.Properties["LastBootUpTime"].Value.ToString();