Getting user's first and last name from AD RRS feed

  • Question

  • User1085970526 posted
    I have an intranet site running with windows authentication, and I would like to greet the user with their full name. What's the best way to find the first and last name values entered in the AD database?

    I guess it needs a DirectorySearcher object, but my AD knowledge stops there.

    Tuesday, March 21, 2006 2:31 PM

All replies

  • User1354132231 posted
    You can get the current user's details by parsing their domain name and performing a search for it.  Here is an example - 'sn' and 'givenName' are last name and first name respectively.

    <%@ Assembly Name="System.DirectoryServices, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"%>
    <%@ Import Namespace="System.DirectoryServices" %>
    <%@ Import Namespace="System.Text" %>
    <script language="c#" runat="server">
    private void Page_Load(object sender, System.EventArgs e)
            string adsPath = "LDAP://server/dc=yourdomain,dc=com";
            //parse the current user's logon name as search key
            string sFilter = String.Format(
                User.Identity.Name.Split(new char[]{'\\'})[1]
            //this is optional, but more efficient
            string[] attribs = new string[]{"cn", "sn", "givenName"};
            using (DirectoryEntry de = new DirectoryEntry(adsPath))
                de.AuthenticationType = AuthenticationTypes.Secure;
                //use explicit only if necessary
                //de.Username = "domain\\user";
                //de.Password = "secret";
                DirectorySearcher ds = new DirectorySearcher(
                    attribs, //set this to null to retrieve all attribs
                SearchResult sr = null;
                //this is a workaround for memory leak in v.1.1
                using (SearchResultCollection src = ds.FindAll())
                    if (src.Count > 0)
                        sr = src[0];
                if(sr == null)
                    msg.Text = "User not found...";
                StringBuilder sb = new StringBuilder();
                //dump everything we have
                foreach (string key in sr.Properties.PropertyNames)
                    if (sr.Properties.Contains(key))
                        foreach (object o in sr.Properties[key])
                            //output every item
                            sb.AppendFormat("{0} : {1}<br>", key, o);
                msg.Text = sb.ToString();
    <form id="main" runat="server">
    Data for user: <%=User.Identity.Name%> <br><br>
    <asp:label id="msg" runat="server" />

    Wednesday, March 22, 2006 9:05 AM