如何获取Windows用户的登录时间? [英] How to get the Windows user's login time?

查看:730
本文介绍了如何获取Windows用户的登录时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中是否有一种方法可以获取当前用户登录的时间?

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

命令提示符中的quser命令将列出有关当前用户的一些基本信息

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

是否存在System属性或可以在c#中访问的东西,我可以从中获取用户的登录时间?

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

我正在通过Environment.UserName属性获取用户名。需要登录时间。

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

我已经尝试过:

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

遇到以下错误:

推荐答案

请确保您包含对<$的引用c $ c> 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;
}

这篇关于如何获取Windows用户的登录时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆