在 C# 中获取本地 Windows 用户登录会话时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/682360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:12:07  来源:igfitidea点击:

Getting Local Windows User login session timestamp in C#

c#.netwindowslogintimestamp

提问by Darragh

I've been trying to look around the various .NET class library's for some where I can get the logged in user of the local machine, either connected to a domain or not. So far

我一直在尝试查看各种 .NET 类库,以便我可以在其中获取本地计算机的登录用户(无论是否连接到域)。迄今为止

System.Security.Principal.WindowsPrincipal LoggedUser = System.Threading.Thread.CurrentPrincipal as 
System.Security.Principal.WindowsPrincipal;
// This returns the username
LoggedUser.Identity.Name

This will return the user's name, however is there any way of getting the session details, something that you would see in AD or user logged in, session duration, etc.. the context of the user, actions such as Workstation locked, the presence of the user basiclly.

这将返回用户名,但是有没有办法获取会话详细信息,您会在 AD 或登录的用户中看到的内容,会话持续时间等。用户的上下文,工作站锁定等操作,存在用户的基本情况。

If you have any idea, it would be much appreciated. Thanks in advance.

如果您有任何想法,将不胜感激。提前致谢。

采纳答案by Aaron Daniels

You can query Active Directory for much of the data that you need through LDAP queries using the System.DirectoryServicesnamespace. For example, the sample below shows the user's last logon time.

您可以使用System.DirectoryServices命名空间通过 LDAP 查询在 Active Directory 中查询所需的大部分数据。例如,下面的示例显示了用户的上次登录时间。

Of course, this only works for domain users.

当然,这只适用于域用户。

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace ADMadness
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectorySearcher search = new DirectorySearcher("LDAP://DC=my,DC=domain,DC=com");
            search.Filter = "(SAMAccountName=MyAccount)";
            search.PropertiesToLoad.Add("lastLogonTimeStamp");


            SearchResult searchResult = search.FindOne();


            long lastLogonTimeStamp = long.Parse(searchResult.Properties["lastLogonTimeStamp"][0].ToString());
            DateTime lastLogon = DateTime.FromFileTime(lastLogonTimeStamp);


            Console.WriteLine("The user last logged on at {0}.", lastLogon);
            Console.ReadLine();
        }
    }
}

回答by JoshBerke

You can get some of that such as start time from WMI look at WMI_LogonSession

您可以从 WMI 查看WMI_LogonSession 中的一些内容,例如开始时间