3
votes

Before i start, i want to make it clear that I'm able to do this using the DirectoryServices namespace. I just want to know how to achieve my below question not using DirectoryServices.

What I'm trying to do is use the DirectoryServices.AccountManagement.UserPrincipal class to partial name search for a user account. The catch is, i would like to get the following properties: EmailAddress, GivenName, MiddleName, SurName, etc. Note: All the properties I'm looking for ARE all exposed in UserPrincipal. here is an example using UserPrincipal without partial name search.

        using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName))
        {
            return user;
        }

From the tutorials I've read, i can partial name search using the following code:

        using (UserPrincipal user = new UserPrincipal(ctx))
        {
            user.SamAccountName = String.Format("*{0}*", userName);

            using (PrincipalSearcher searcher = new PrincipalSearcher())
            {
                searcher.QueryFilter = user;
                return searcher.FindAll();
            }
        }

The problem with this is when i iterate through the PrincipalSearcher collection (searcher), it's of the Principal data type. And the Principal data type doesn't contain any of the properties i mentioned above.

So my question is, how can i use UserPrincipal to partial name search and get the properties that are NOT exposed in the Principal data type? Or is this not possible?

1

1 Answers

2
votes

Can't you cast the Principal objects to UserPrincipal objects? Maybe catching invalid casts.

    return searcher.FindAll().Cast<UserPrincipal>();

Principal seems to be an abstract base class http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principal(v=vs.110).aspx