Get the date and time the computer called

Asked

Viewed 579 times

6

I would like a method to get the date and time the computer last connected with (c# windows form application).

4 answers

3

You can consult the performance counter which indicates how long the system is active (I mean, how long has it been since the last time Windows started and subtract 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 can do it using the function 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 registration key of Windows:

"HKEY_LOCAL_MACHINE SOFTWARE Microsoft Windows NT Currentversion Perflib Currentlanguage Counter".

Finally, the original method would be:

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);
}
  • This works even if the user modifies the current date?

  • 1

    In that case the problem will be the call from Datetime.Now that reads the system clock.

  • 1

    @Felipeavelar relativemente ao counter I couldn’t find any sources, but I was testing on a VM and changing the clock nay alters the counter

  • I got it, but I was talking more like DateTime.Now even...

2


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;
    }

Reference to dll System.Management to the project is required.

Another alternative is using Tickcount:

    private static DateTime GetLastBootUpTimeByTickCount()
    {
        DateTime now = DateTime.Now;
        DateTime boot = now - TimeSpan.FromMilliseconds(Environment.TickCount);

        return boot;
    }

Note: The problem is that this other alternative with Tickcount will function for only 25 days due to Tickcount being of type Int32.

0

If your computer never spends more than 49.7 days on:

  • Get the number of milliseconds passed from boot to current;
  • Subtract this number from the current date.

This code can be expressed on a line:

var bootTime = DateTime.Now.Subtract(
                   TimeSpan.FromMilliseconds(
                       System.Environment.TickCount));

Sources:

Gettickcount Function, MSDN
How to know when was Windows Started or shutdown?, Stackoverflow

0

I read some examples where you can use the namespace System.Diagnostics.Eventing.Reader to access the logs of Event Viewer and get that information.

Although I don’t have an environment to try a local test I believe it would be interesting to take a look at these references.

You use the class Eventlogquery to create the desired query on Event Viewer and reads the data using the class Eventlogreader.

Below an example 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()));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.