C#从AD获取pwdLastSet

时间:2017-12-11 11:28:08

标签: c# wpf active-directory mahapps.metro

我试过了" pwdLastSet"来自AD,但数据转换有问题。

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

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

1 个答案:

答案 0 :(得分:1)

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

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