I would like a method to get the date and time the computer last connected to (c # windows form application).
I would like a method to get the date and time the computer last connected to (c # windows form application).
Using the ManagementObjectSearcher.
using System.Management;
using System.Linq;
public static DateTime GetLastBootUpTime()
{
DateTime lastBootUpTime = new DateTime();
SelectQuery query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject mo in searcher.Get())
{
lastBootUpTime = ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
}
return lastBootUpTime;
}
You need to reference the System.Management dll to the project.
Another alternative is to use TickCount:
private static DateTime GetLastBootUpTimeByTickCount()
{
DateTime now = DateTime.Now;
DateTime boot = now - TimeSpan.FromMilliseconds(Environment.TickCount);
return boot;
}
Note: The problem is that this alternative with TickCount will run for only 25 days because the TickCount is Int32 type.
You can check the performance counter that indicates how long the system has been active (that is, how long has it been since the last time Windows started and subtracts that time from the current date:
using (var counterTempoActivo = new PerformanceCounter("System", "System Up Time"))
{
counterTempoActivo.NextValue();
TimeSpan tempoActivo = TimeSpan.FromSeconds(counterTempoActivo.NextValue());
return DateTime.Now.Subtract(tempoActivo);
}
Extra :
If you need to ensure the correct location of strings you can do so by using the PdhLookupPerfNameByIndex :
// Importe a função
[DllImport("pdh.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern UInt32 PdhLookupPerfNameByIndex(string szMachineName, uint dwNameIndex, StringBuilder szNameBuffer, ref uint pcchNameBufferSize);
// Este método usa a função importada e procura a *string* associada ao ID passado
public string ProcurarStringLocalizada(uint id)
{
StringBuilder buffer = new StringBuilder(1024);
uint bufSize = (uint)buffer.Capacity;
PdhLookupPerfNameByIndex(null, id, buffer, ref bufSize);
return buffer.ToString();
}
In this case, the ID for the string "System" is 2, and for the string "System Up Time" is 674. These IDs can be found in the following Windows registry key:
"HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ Perflib \ CurrentLanguage \ Counter".
Finally, the original method would look like:
const uint systemId = 2;
const uint upTimeId = 674;
string categoria = ProcurarStringLocalizada(systemId);
string counter = ProcurarStringLocalizada(upTimeId);
using (var counterTempoActivo = new PerformanceCounter(categoria, counter))
{
counterTempoActivo.NextValue();
TimeSpan tempoActivo = TimeSpan.FromSeconds(counterTempoActivo.NextValue());
return DateTime.Now.Subtract(tempoActivo);
}
If your computer never goes more than 49.7 days on:
This code can be expressed in a line:
var bootTime = DateTime.Now.Subtract(
TimeSpan.FromMilliseconds(
System.Environment.TickCount));
Sources:
GetTickCount function , MSDN
How did you know when Windows started or shutdown? , StackOverflow
I have read some examples where you can use namespace System.Diagnostics. Eventing.Reader to access the Event Viewer logs and obtain this information.
Although I do not have the environment to try a local test, I think it would be interesting to take a look at these references.
You use the EventLogQuery to create the query you want in the Event Viewer and then read the data using the EventLogReader
Below is a sample code:
EventLogQuery query = new EventLogQuery("Application", PathType.LogName, "*[System[(Level = 3)]]");
EventLogReader reader = new EventLogReader(query);
EventRecord eventRecord;
while ((eventRecord = reader.ReadEvent()) != null)
{
Console.WriteLine(String.Format("{0} - {1}",
eventRecord.TimeCreated,
eventRecord.FormatDescription()));
}