我用 C# 编写代码来查找 Active Directory 中的上次密码更改日期和时间。我已经能够通过一些示例找到日期,但找不到正确的时间戳。有人可以帮忙解决这个问题吗?到目前为止我的代码是:
DirectoryEntry de = (DirectoryEntry)foundUser.GetUnderlyingObject();
if (de.Properties["pwdLastSet"].Value != null)
{
LargeInteger liAcctPwdChange = de.Properties["pwdLastSet"].Value as LargeInteger;
long dateAcctPwdChange = (((long)(liAcctPwdChange.HighPart) << 32) + (long)liAcctPwdChange.LowPart);
Label1.Text = DateTime.FromFileTime(dateAcctPwdChange).ToShortDateString();
}
尝试改变
long dateAcctPwdChange = (((long)(liAcctPwdChange.HighPart) << 32) + (long)liAcctPwdChange.LowPart);
Label1.Text = DateTime.FromFileTime(dateAcctPwdChange).ToShortDateString();
对此
long dateAcctPwdChange = (((long)(liAcctPwdChange.HighPart) << 32) + (uint)liAcctPwdChange.LowPart);
Label1.Text = DateTime.FromFileTimeUtc(dateAcctPwdChange).ToString();
将最后一个
long
更改为 uint
并将 FromFileTime
更改为 FromFileTimeUtc
有关 MSDN 的快速参考示例:https://msdn.microsoft.com/en-us/library/ms180872(v=vs.90).aspx
如果有人仍在寻找工作代码,这是我的工作版本:
using System;
using System.DirectoryServices.AccountManagement;
class Program
{
static void Main()
{
// Set up a PrincipalContext to connect to your Active Directory domain
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "YourDomain"))
{
// Find the user by their username
UserPrincipal user = UserPrincipal.FindByIdentity(context, "Username");
if (user != null)
{
// Retrieve the "Password last set" attribute
DateTime? passwordLastSet = user.LastPasswordSet;
if (passwordLastSet != null)
{
Console.WriteLine("Password Last Set: " + passwordLastSet.Value.ToString());
}
else
{
Console.WriteLine("Password Last Set information is not available.");
}
}
else
{
Console.WriteLine("User not found in Active Directory.");
}
}
}
}