1

Is there a way in C# to get the time when the current user logged in?

A command called quser in command prompt will list some basic information about current users, including LOGON TIME.

Is there a System property or something I can access in c# which I can get the user's login time from?

I am getting username by Environment.UserName property. Need the login time.

I've tried this:

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

Console.WriteLine("Login Time: {0}",GetLastLoginToMachine(Environment .MachineName , Environment.UserName));
public static DateTime? GetLastLoginToMachine(string machineName, string userName)
{
    PrincipalContext c = new PrincipalContext(ContextType.Machine, machineName);
    UserPrincipal uc = UserPrincipal.FindByIdentity(c, userName);
    return uc.LastLogon;
}

Got the following errors:

Visual Studio build errors

Nic
  • 12,220
  • 20
  • 77
  • 105

3 Answers3

2

You can get the LastUserLogon time from the following namespace.

using System.DirectoryServices.AccountManagement;

Try

DateTime? CurrentUserLoggedInTime = UserPrincipal.Current.LastLogon;

You can get the account information as well :

string userName = WindowsIdentity.GetCurrent().Name.Split('\\')[1];
string machineName = WindowsIdentity.GetCurrent().Name.Split('\\')[0];
Prajeesh T S
  • 158
  • 1
  • 9
1

Make sure you include the reference to System.DirectoryServices.AccountManagement:

References Manager

Then you can do this to get the last logon time:

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;
}
Nic
  • 12,220
  • 20
  • 77
  • 105
0

You can query WMI:

// using System.Management;

private static Dictionary<string, DateTime> getMachineLogonName(string machine)
{
    var loggedOnUsers = new Dictionary<string, DateTime>();


    ManagementScope scope = new ManagementScope(String.Format(@"\\{0}\root\cimv2", machine));

    SelectQuery sessionQuery = new SelectQuery("Win32_LogonSession");

    using (ManagementObjectSearcher sessionSearcher = new ManagementObjectSearcher(scope, sessionQuery))
    using (ManagementObjectCollection sessionMOs = sessionSearcher.Get())
    {

        foreach (var sessionMO in sessionMOs)
        {
            // Interactive sessions
            if ((UInt32)sessionMO.Properties["LogonType"].Value == 2)
            {
                var logonId = (string)sessionMO.Properties["LogonId"].Value;
                var startTimeString = (string)sessionMO.Properties["StartTime"].Value;
                var startTime = DateTime.ParseExact(startTimeString.Substring(0, 21), "yyyyMMddHHmmss.ffffff", System.Globalization.CultureInfo.InvariantCulture);

                WqlObjectQuery userQuery = new WqlObjectQuery(@"ASSOCIATORS OF {Win32_LogonSession.LogonId='" + logonId + @"'} WHERE AssocClass=Win32_LoggedOnUser");

                using (var userSearcher = new ManagementObjectSearcher(scope, userQuery))
                using (var userMOs = userSearcher.Get())
                {
                    var username = userMOs.OfType<ManagementObject>().Select(u => (string)u.Properties["Name"].Value).FirstOrDefault();

                    if (!loggedOnUsers.ContainsKey(username))
                    {
                        loggedOnUsers.Add(username, startTime);
                    }
                    else if(loggedOnUsers[username]> startTime)
                    {
                        loggedOnUsers[username] = startTime;
                    }
                }
            }
        }

    }

    return loggedOnUsers;
}

Then just call the method with target machine name:

var logins = getMachineLogonName(".");
Serge
  • 3,986
  • 2
  • 17
  • 37