Home > other >  AD request with C#
AD request with C#

Time:02-23

I'm trying to get all users from AD and their passwords expiration dates with the following code, but got the error.

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

The code:

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

CodePudding user response:

The exception means that you're calling GetUnderlyingObject() on a UserPrincipal object that hasn't been saved.

You're calling GetUnderlyingObject() on the user object that you created as the filter for your PrincipalSearcher. I think you intended to call it on result:

DirectoryEntry entry = (DirectoryEntry)result.GetUnderlyingObject();
  • Related