C# - Pegar o UpTime do SO

Ok vamos pegar o tempo total que o sistema esta ligado !


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
 
namespace wmi_get_uptime
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        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;
        }
 
        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;
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
 
            //Como chamar !
            textBox1.Text = GetSystemUptime().ToString();
 
        }
 
    }
}

Segue ScreenShot =]


Fácil não ? Qualquer coisa de um grito !

0 comentários:

Postar um comentário