Getting user's first and last name from AD

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.

Thanks,
John

John Hoge
SeaEagle.com Inflatable Boats
0
John
3/21/2006 6:31:55 PM
asp.net.active-directory-ldap 2291 articles. 0 followers. Follow

1 Replies
986 Views

Similar Articles

[PageSpeed] 25

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" %>
 
<HTML>
<HEAD>
<script language="c#" runat="server">
 
private void Page_Load(object sender, System.EventArgs e)
{
    if(!Page.IsPostBack)
    {
        string adsPath = "LDAP://server/dc=yourdomain,dc=com";
 
        //parse the current user's logon name as search key
        string sFilter = String.Format(
            "(&(objectCategory=person)(sAMAccountName={0}))",
            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(
                de,
                sFilter,
                attribs, //set this to null to retrieve all attribs
                SearchScope.Subtree
                );
 
            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...";
                return;
            }
 
            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();
        }
    }
}
 
</script>
</HEAD>
<BODY>
<form id="main" runat="server">
 
Data for user: <%=User.Identity.Name%> <br><br>
 
<asp:label id="msg" runat="server" />
</form>
</BODY>
</HTML>


Ryan Dunn
Weblog
The Book
LDAP Programming Help
0
dunnry
3/22/2006 1:05:18 PM
Reply:

Similar Artilces:

Get user's first and last name from Active directory.
Hi,I'm trying to get user's first and last name from AD to display in my welcome page. I'm using Visual Studio 2005. In my login page I have login control and I'm using forms authentication against LDAP.So I don't have to store user data. Any help would be greatly appreciated.   DirectoryEntry objOU = new DirectoryEntry(",%20DC=domain,%20DC=something,%20DC=net%20or%20com>/">LDAP://CN=your user name, OU=users group>, DC=domain, DC=something, DC=net or com"); string name = objOU.Properties["givenName"].Value.ToString(); string...

How to get domain user's first name, last name and e-mail address
Hi everyone, I am able to retrieve the domain/user ID by setting <authentication mode="Windows"/> in the Web.config file, and with the following code in my Default.aspx.,cs page: string strName = Request.ServerVariables["AUTH_USER"]; I would also like to retrieve the users first name, last name and e-mail address from their domain profile, if possible.  Can anyone help me with a code example?  I'm somewhat new to C#/.NET/OOP so if you have it in "C# for Dummies" format, I would be very thankful! Thanks in advance for any help that i...

Getting the user's first and last name
I'm using the login control and I'm getting the username without a problem (<asp:LoginName ID="LoginName1" runat="server" />) but how do I get the user's first and last name (or any other information)?  I do have the user's information stored in a database.  I'm not utilizing Profile schema either.Thanks. Use the MemberShip class to get the user information. http://msdn.microsoft.com/en-us/library/tw292whz.aspx*** If this post helps you, then Mark this post as Answer ***...

get user's windows login name "SAMaccount" and compare with Active Directory cn, roles...
OK, This one has been plaguing me for this entire day. Here is the background info. I know how to query Active directory, but I need to get the windows login name to use with the searchfilter in AD. My site has annonymous access checked in IIS. Before anyone says to uncheck this...it is a requirement to have it checked. If a user who is not on our domian (in Active Directoyr) navigates to any page in my web app, they will be redirected to Login.aspx. I have been using WindowsIdentity and User.Identity.Name. I just cannot get the login name! I have gotten the asp.net maching name listed in...

how to create AD users in 'Users' section of "Active Directory Users and Computers" window.
 I can create new AD users but not in 'Users' section in "Active Directory Users and Computers" window of windows server 2003.Here is the related part of my code: System.DirectoryServices.DirectoryEntry myAD = new DirectoryEntry("LDAP://" + xxx + "/Users"); //If I put "/Users" then it throws exception, otherwise it works. But, users are not created in 'Users' folder. DirectoryEntry newUser = myAD.Children.Add("CN=" + username, "user"); newUser.Properties["d...

User's first and last name
What would be the simplest way to add the user's first and last name to the registration process?I noticed there was a comment column in membership user.  Would it be easy to add xml document to this field?Thanks!Rob you can check the link below:Extend the MembershipUser class http://forums.asp.net/43/ShowForum.aspx...

Get User's Group on Active Directory
Hi! We have two servers, one running using an LDAP and the other using WinNT. I got the group/s of a particular user when logging on LDAP, but can't get the groups on WinNT. So my question is how can i return the group/s of a the logged user? DirectoryEntry entry = new DirectoryEntry("WinNT://DOMAIN/" + userLogged);return entry.Properties["FullName"].Value.ToString();// I tried entry.Properties["Group"].Value.ToString(), but to no effect.thanks. It's a little troublesome, but you should .Invoke the IADsMember::Groups method.  Read this entry here on how to do it and r...

How to determine an Active Directory user's full name for use in Visual Basic code
I'm looking for a way to pull specific user information from Active Directory based upon the logon of a user. For example: I would log into my company's Intranet using jsmith@mycompany.net, but on the next page I would like John Smith to instead be displayed to welcome and more clearly identify the logged in user. For project purposes, the user's full name, not log on name, would be written to a SQL DB for quick identification. I have been to countless forums and blogs looking for an answer, but I am very new asp.net programming so I'm definitely missing some vital informa...

Why can't I get a User's Name?
Hi, I'm having real issues just getting the username of any user. To try to simplify it, I made my code like this and it still won't get anything. Can anyone help? <%@ Page Language="VB" %> <script runat="server"> sub page_load testing.text = User.Identity.Name end sub </script> <html> <head> </head> <body> <form runat="server"> <!-- Insert content here --> <asp:label id = "testing" runat="server"> </as...

Getting first name and last name from Windows logged in user
 I'm sure there must be an easy way of getting the actual first name and last name from an Windows domain\username via the Windows Identity or Principal object, but I can't seem to figure it out. Does anyone have any examples of this? try this: HttpContext.Current.User.Identity.Name  Thanks - tried that...it returns nothing or domain\loginName :( Please check that on the site properties window (in IIS Admin console), in the security tab, click on the modify or edit button in the authentication and anonymous access group and make sure only the "Windows Inte...

unable to get groups name from user name in Active Directory
good day to all, I am looking for to find group name for the current user but unable to find it using following code. it returns me the 1st group in the list .however it is returning all groups using for each loop with the below function. what i m missing . please help Private Function GetGroupName() as string Dim dEntry As DirectoryEntry = New DirectoryEntry(sADPath, sUserName, sPassword) Dim sResult As SearchResult Try'Pass directory entry object for searchingDim dSearch As New DirectorySearcher(dEntry) dSearch.SearchRoot = dEntry dSearch.Filter = ("(objectCl...

Open file in browser or application getting the page's name as the file's name
Hi, I'm am trying to get a file to open in either a browser or application depending on the mime type. I'am using the following code in the page load. protected void Page_Load(object sender, EventArgs e){ if (!IsPostBack)    { DocumentInfo document = (DocumentInfo)Session["View_Document"]; StreamFile(document.Document, document.DocumentName, document.FileType.MimeType); } } }private void StreamFile(byte[] fileData, string originalFileName, string mimeType) { try { Response.Clear(); Response.ContentType = mimeType; Response.AddHeader("Con...

Get user first and last name?
All  I can use the following to get my users logon name, If User.Identity.IsAuthenticated Then Label1.Text = "Welcome, <B>" + User.Identity.Name + "</B>" Label1.Text = Label1.Text & "Welcome, <B>" + Request.LogonUserIdentity.Name + "</B>" ElseResponse.Write("sorry") End If how do i now get thier first and last names thanks gibbo Plz explain  complete requirement and database Entity..?  Thanks & Regards,Murthy. I am not interacting with a database in any way, I know my us...

changes made from one user's webpart's page, effects all user's
 I am just doing this offline right now in Visual Web Developer Express 2008I created the login inonce in the memberpage area, people can modify their webpart page. I created several users to test this out.  I loaded it in a browser.When I make changes as logged in user "A" .  Then logout and login as user "B", user "B,s" webpart page has been changed to user "A".This goes true for whomever I log in as.  It changes for everyone.Is there something specific I need to do in order to get everyone's changes to be unique for them...

Web resources about - Getting user's first and last name from AD - asp.net.active-directory-ldap

Resources last updated: 12/9/2015 2:51:45 PM