How to get the Windows user's login time?

断了今生、忘了曾经 提交于 2020-04-05 05:25:13

问题


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:


回答1:


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

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



回答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];



回答3:


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(".");


来源:https://stackoverflow.com/questions/42480492/how-to-get-the-windows-users-login-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!