使用 C# 的 AD 请求

AD request with C#

我尝试使用以下代码从 AD 获取所有用户及其密码到期日期,但出现错误。

System.InvalidOperationException: 'The Principal object must be persisted before this method can be called.'

代码:

PrincipalContext domain = new PrincipalContext(ContextType.Domain,"AAA","OU=USERS,OU=TEST,DC=AAA,DC=AA, DC=A");
UserPrincipal user = new UserPrincipal(domain);
PrincipalSearcher pS = new PrincipalSearcher(user);

foreach (UserPrincipal result in pS.FindAll())
    {
    if (result != null && result.DisplayName != null)
        {
        DirectoryEntry entry = (DirectoryEntry)user.GetUnderlyingObject();
        IADsUser native = (IADsUser)entry.NativeObject;
        Console.WriteLine(result.DisplayName, native.PasswordExpirationDate);
        }
     }

异常意味着您正在对尚未保存的 UserPrincipal 对象调用 GetUnderlyingObject()

您在 user 对象上调用 GetUnderlyingObject(),该对象是您为 PrincipalSearcher 创建的过滤器。我认为您打算在 result:

上调用它
DirectoryEntry entry = (DirectoryEntry)result.GetUnderlyingObject();