,可以使用System.DirectoryServices命名空间中的DirectoryEntry和DirectorySearcher类来实现。
首先,需要引用System.DirectoryServices命名空间:
using System.DirectoryServices;
然后,可以使用以下代码来获取AD用户的创建日期:
string domainPath = "LDAP://DC=example,DC=com"; // 替换为你的域路径
string username = "username"; // 替换为要查询的用户名
DirectoryEntry entry = new DirectoryEntry(domainPath);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = $"(&(objectClass=user)(sAMAccountName={username}))";
searcher.PropertiesToLoad.Add("whenCreated");
SearchResult result = searcher.FindOne();
if (result != null)
{
DateTime createdDate = (DateTime)result.Properties["whenCreated"][0];
Console.WriteLine($"AD用户{username}的创建日期是:{createdDate}");
}
else
{
Console.WriteLine($"未找到AD用户{username}");
}
上述代码中,需要将domainPath
替换为你的域路径,例如LDAP://DC=example,DC=com
。同时,将username
替换为你要查询的用户名。
代码中使用DirectoryEntry
类和DirectorySearcher
类来连接和搜索AD域。Filter
属性用于指定搜索条件,这里使用了用户名进行过滤。PropertiesToLoad
属性用于指定要加载的属性,这里加载了whenCreated
属性。
通过调用searcher.FindOne()
方法执行搜索,并将结果存储在SearchResult
对象中。如果找到了匹配的用户,可以通过result.Properties["whenCreated"][0]
来获取创建日期。
最后,将创建日期打印出来或进行其他操作。
请注意,上述代码仅适用于Windows环境下的AD域。如果你的环境不同,可能需要进行相应的调整。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云