0

I need to get the current user login time, intended as when the current user session started, now I use this cmd code to get it:

for /f "skip=1 tokens=5*" %a in ('quser %username%') do @echo USER SESSION STARTED AT: %b

I want to find a way to get it using C#, but until now I only found ways to get the last time the user logged in inserting the password (the two timestamps are equal if the last user login happened using the password, but not if the user automatically logged in or he used a PIN on Windows 10).

How can I do it (apart from parsing quser.exe output)?

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Does this answer your question? [How to get the Windows user's login time?](https://stackoverflow.com/questions/42480492/how-to-get-the-windows-users-login-time) – Jedi_Maseter_Sam Jan 21 '20 at 23:31

1 Answers1

0

May be you can try something like this:

using System.DirectoryServices.AccountManagement;

public static DateTime? GetLastLoginToMachine(string machineName, string userName)
{
    PrincipalContext c = new PrincipalContext(ContextType.Machine, machineName);
    UserPrincipal uc = UserPrincipal.FindByIdentity(c, userName);
    return uc.LastLogon;
}
Nitin
  • 1
  • Thanks for your answer. I already tried this code, it's the equivalent of "last access" field of cmd code "net user %username%", it gives the last time current user inserted the password and ignores automatic logins or logging in using a pin. – Guido Mazzone Jan 22 '20 at 00:00