c# - 在 C# 中获取本地 Windows 用户登录 session 时间戳

标签 c# .net windows authentication timestamp

我一直在尝试查看各种 .NET 类库,寻找一些可以获取本地计算机登录用户的地方,无论是否连接到域。 到目前为止

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

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

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

最佳答案

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

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

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

关于c# - 在 C# 中获取本地 Windows 用户登录 session 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/682360/

相关文章:

c# - 检测使用/滥用 String.Concat 的工具(应该使用 StringBuilder 的地方)

c++ - 删除 ListView 中特定项目的复选框

c# - tabcontrol ownerdraw 更改 tabcontrol 的边框样式

c# - 按下按钮时不激活窗口

C# .Net WinForms 应用程序 : anonymous collection- how to caste return type

c - SendMessage 适用于 WM_CHAR,但不适用于 WM_KEYDOWN

windows - 如何在 React Native Windows 中将 "Windows"加载到 Chakra 命名空间?

c# - .Net Rally.RestApi 创建 Rally 测试文件夹时出现错误 "Not authorized to perform action: Invalid key"

c# - Xamarin 表格 : Left Side Outline Border on image

c# - 这两个委托(delegate)声明有什么区别?