Retrieve the User Properties

This method retrieves the firstName, lastName, emailAddress, telephone, and address properties for a given user name (passed as a string). This method finds the user principal object via the FindByIdentity method and uses that object's properties to populate the strings for each property.

        internal static void GetUserProperties(string user, out string firstName, out string lastName, out string emailAddress, out string telephone, out string address)
        {
            // Creating the PrincipalContext
            PrincipalContext principalContext = null;
            try
            {
                principalContext = new PrincipalContext(ContextType.Domain, "fabrikam", "DC=fabrikam,DC=com");
            }
            catch (Exception e)
            {
                MessageBox.Show("Failed to create PrincipalContext. Exception: " + e);
                Application.Exit();
            }

            //Getting the properties of the user
            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, user);
            firstName = null; lastName = null; emailAddress = null; telephone = null; address = null;
            if (userPrincipal != null)
            {
                if (userPrincipal.GivenName != null)
                    firstName = userPrincipal.GivenName;

                if (userPrincipal.Surname != null)
                    lastName = userPrincipal.Surname;

                if (userPrincipal.EmailAddress != null)
                    emailAddress = userPrincipal.EmailAddress;

                if (userPrincipal.VoiceTelephoneNumber != null)
                    telephone = userPrincipal.VoiceTelephoneNumber;

                if (userPrincipal.GetUnderlyingObjectType() == typeof(DirectoryEntry))
                {
                    DirectoryEntry entry = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
                    string userAddress = (string)entry.Properties["streetAddress"].Value;
                    if (userAddress != null && userAddress.Length > 0)
                        address = userAddress;
                }

            }
            else
            {
                MessageBox.Show("Could not find the user [" + user + "]");
                return;
            }

        }

See Also

Reference

System.DirectoryServices.AccountManagement

Concepts

About System.DirectoryServices.AccountManagement
Using System.DirectoryServices.AccountManagement

Send comments about this topic to Microsoft.

Copyright © 2008 by Microsoft Corporation. All rights reserved.