C# - Use WMI to get the system's up-time

  • 0 Replies
  • 144 Views

0 Members and 1 Guest are viewing this topic.

Offline Omega

    *
  • The Boss (Admin)
  • Black Hat Sec Member
  • Telegram: @BLACKHATSEC_FORUM
  • Posts: 190
  • Popularity: +1/-0
  • God of Malware
    • View Profile
    • Awards
« on: March 14, 2022, 09:27:03 AM »
C# - Use WMI to get the system's up-time

Code
//method to parse the CIM_DATETIME value returned from a WMI call to a .Net readable format
/// <summary>
/// method used to parse the datetime returned from a WMI call. The date format
/// that WMI works well with is CIM_DATETIME. The date is stored as a humany readable
/// format, such as 20100101161959.115081+060 (This represents 01/01/2010 16:19:59) This
/// method converts CIM_DATETIME values into .Net readable DateTime object
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
private DateTime ParseCIM(string date)
{
    //datetime object to store the return value
    DateTime parsed = DateTime.MinValue;

    //check date integrity
    if (date != null && date.IndexOf('.') != -1)
    {
        //obtain the date with miliseconds
        string newDate = date.Substring(0, date.IndexOf('.') + 4);

        //check the lenght
        if (newDate.Length == 18)
        {
            //extract each date component
            int y = Convert.ToInt32(newDate.Substring(0, 4));
            int m = Convert.ToInt32(newDate.Substring(4, 2));
            int d = Convert.ToInt32(newDate.Substring(6, 2));
            int h = Convert.ToInt32(newDate.Substring(8, 2));
            int mm = Convert.ToInt32(newDate.Substring(10, 2));
            int s = Convert.ToInt32(newDate.Substring(12, 2));
            int ms = Convert.ToInt32(newDate.Substring(15, 3));

            //compose the new datetime object
            parsed = new DateTime(y, m, d, h, mm, s, ms);
        }
    }

    //return datetime
    return parsed;
}

/// <summary>
/// method to get the current systems up-time, returned in a Timespan value
/// </summary>
/// <returns></returns>
public TimeSpan GetSystemUptime()
{
    //timespan object to store the result value
    TimeSpan up = new TimeSpan();

    //management objects to interact with WMI
    ManagementClass m = new ManagementClass("Win32_OperatingSystem");

    //loop throught the WMI instances
    foreach (ManagementObject instance in m.GetInstances())
    {
        //get the LastBootUpTime date parsed (comes in CIM_DATETIME format)
        DateTime last = ParseCIM(instance["LastBootUpTime"].ToString());

        //check it value is not DateTime.MinValue
        if (last != DateTime.MinValue)
            //get the diff between dates
            up = DateTime.Now - last;
    }

    //return the uptime TimeSpan
    return up;
}
  • Discord: BLACK HAT SEC#5222
  • [+]
  • [-]

  •