C# 从 AD 获取 pwdLastSet

C# get pwdLastSet from AD

我尝试从 AD 获取 "pwdLastSet",但数据转换有问题。

DirectoryEntry de = new DirectoryEntry();
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + Login + "))";
ds.SearchScope = SearchScope.Subtree;
SearchResult rs = ds.FindOne();

if (rs.GetDirectoryEntry().Properties["samaccountname"].Value == null)
{
    var window = Application.Current.Windows.OfType<MetroWindow>().FirstOrDefault();
    if (window != null)
        await window.ShowMessageAsync("error!", "error");
    return;
}
else
{
        TextBox_Password.Text = rs.GetDirectoryEntry().Properties["pwdLastSet"].Value.ToString();
}

在这里,我得到:System.__ComObject

我也试过:

long value = (long)rs.Properties["pwdLastSet"][0];
DateTime pwdLastSet = DateTime.FromFileTimeUtc(value);
value = long.Parse(TextBox_Password.Text);

在这里,我得到异常:输入字符串格式不正确

您应该将 TextBox_Password.Text 属性 设置为检索日期的字符串表示形式,而不是调用 long.Parse:

long value = (long)rs.Properties["pwdLastSet"][0];
DateTime pwdLastSet = DateTime.FromFileTimeUtc(value);
TextBox_Password.Text = pwdLastSet.ToString();