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

2023-09-05 02:51:45 作者:放肆小青年

我一直在试图寻找周围的各种.NET类库的一些在那里我可以得到记录在本地机器的用户,无论是连接到域或没有。 到目前为止

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

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

这将返回用户的名称,但有什么办法获得会话细节的东西,你会在AD或用户看到登录,会话持续时间等。用户的情况下,如工作站操作锁定中,用户basiclly的presence。

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.

如果您有任何想法,这将是更AP preciated。 先谢谢了。

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

推荐答案

您可以查询很多数据的Active Directory,您使用的 System.DirectoryServices中命名空间。例如,下面的示例显示了用户的最后一次登录时间。

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

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

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();
        }
    }
}
 
精彩推荐