Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1742
  • Last Modified:

ASP.NET, C#, Active Directory - How do I display the fullname?

First off: I am using ASP.NET C# and Active Directory.

My question is... I have a login system that works off of active directory / windows auth.  When the person logs in I currently have their login name showing (i.e. Welcome smithjo) I would like to show their full name (i.e. Welcome Joe Smith!).  I have been looking all over and trying many examples of how to do this with no luck.

Can anyone help me out?  Currently I am using this code, which is throwing the error: System.NullReferenceException: Object reference not set to an instance of an object.

Code:

string ldapPath = "LDAP://test.com/OU=staff,DC=test,DC=com";
        DirectoryEntry currentUser = new DirectoryEntry(ldapPath);
 
        if (currentUser != null)
        {
            string firstName = currentUser.Properties["givenName"].Value.ToString();
            string lastName = currentUser.Properties["sn"].Value.ToString();
            lblFirstName.Text = firstName;
            lblLastName.Text = lastName;
        }
        else
        {
            lblUsername.Text = "Unknown User";
        }

Open in new window

0
toneez
Asked:
toneez
  • 2
1 Solution
 
Daniel ReynoldsSoftware Applications Developer / IntegratorCommented:
try displayname
currentUser.Properties["displayName"].Value.ToString();
0
 
toneezAuthor Commented:
I tried displayName as well already and it does not solve the issue unfortunately.
0
 
toneezAuthor Commented:
Well finally after enough tinkering around I figured this out.  I will attach the working code for anyone else who runs across this.
string userName = User.Identity.Name;
        string ldapPath = "LDAP://test.com/OU=Staff,DC=test,DC=com";
        DirectoryEntry rootEntry = new DirectoryEntry(ldapPath);
        using (DirectorySearcher ds = new DirectorySearcher(rootEntry, "(samAccountName=" + userName + ")"))
        {
            SearchResult result = ds.FindOne();
            if (result != null)
            {
                ResultPropertyValueCollection resultValues = result.Properties["givenName"];
                if (resultValues.Count > 0)
                {
                    lblUsername.Text = (string)resultValues[0];
                }
                else
                {
                    lblUsername.Text = "Unknown User";
                }
            }
        }

Open in new window

0

Featured Post

Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now