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
  • 11,374
  • 19
  • 75
  • 96
Kuharan Bhowmik
  • 117
  • 1
  • 12
  • http://stackoverflow.com/a/1475066/6356434 – Alex Feb 27 '17 at 08:03
  • 1
    @Nicholas using System.DirectoryServices; The type or namespace name 'DirectoryServices' does not exist in the namespace 'System' (are you missing an assembly reference?) Raised the question again since that version is too old – Kuharan Bhowmik Feb 27 '17 at 08:18
  • 1
    Have you added the reference to System.DirectoryServices to your project? – Daniel Hollinrake Feb 27 '17 at 08:38
  • @DanielHollinrake I have added and got errors that the DirectoryServices does not exist in the namespace 'System' – Kuharan Bhowmik Feb 27 '17 at 08:40
  • 1
    Which .Net version you have selected in Project Properties? If you are using "Client" version of the libraries, you may have some problems - in that case, try switching your project to "full" framework. – quetzalcoatl Feb 27 '17 at 08:48
  • @quetzalcoatl If I change my .NET version in the project properties then my other components will not work. – Kuharan Bhowmik Feb 27 '17 at 08:52

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
  • 11,374
  • 19
  • 75
  • 96
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,808
  • 2
  • 16
  • 32