Wednesday, 16 May 2012

Read a property from Active Directory

public static string GetUserProperty(string user, string propertyName)
        {
            using (var context = new PrincipalContext(ContextType.Domain, “yourDomainName”)
            {
                UserPrincipal userPrincipal = new UserPrincipal(context);
                userPrincipal.SamAccountName = user;

                PrincipalSearcher principalSearcher = new PrincipalSearcher();
                principalSearcher.QueryFilter = userPrincipal;

                Principal searchResults = principalSearcher.FindOne();

                if (searchResults != null)
                {
                    return searchResults.GetProperty(propertyName);
                }
            }

            return string.Empty;
        }

No comments:

Post a Comment