Julien Pinquié

ASP.NET, C#, SQL Server, Windows Live

How to get domain user information from Active Directory in C#

First, we have to know the user connection name (here from an ASP.NET page).

string principal = this.Context.User.Identity.Name;

 


Then we have to define some stuff :

  • search filter including object type and connection name,
  • domain,
  • properties to retrieve from Active Directory.
string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", principal);
string domain = "DOMAIN";
string[] properties = new string[] { "fullname" };

 


To search in Active Directory, we need the following objects :

  • DirectoryEntry : represents a node or object in the Active Directory hierarchy,
  • DirectorySearcher : performs queries against Active Directory Domain Services.
DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.SearchScope = SearchScope.Subtree;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.PropertiesToLoad.AddRange(properties);
searcher.Filter = filter;
 
SearchResult result = searcher.FindOne();
DirectoryEntry directoryEntry = result.GetDirectoryEntry();

 


Finally, once information is retrieved in the DirectoryEntry object, we can get the details of each property defined.

string displayName = directoryEntry.Properties["displayName"][0].ToString();
string firstName = directoryEntry.Properties["givenName"][0].ToString();
string lastName = directoryEntry.Properties["sn"][0].ToString();
string email = directoryEntry.Properties["mail"][0].ToString();
Posted: Feb 06 2008, 12:07 PM by jpinquie | with 57 comment(s) |
Filed under: ,

Comments

Justin-Josef Angel [MVP] said:

OK, And?

This is basically just a copy & paste of some code. You never even tried to explain what "Context" is, what "User" is, and what "Identity" is.

Additionally, You just wrote some LDAP query without even so much as noting it.

What's the added value of this post?

# February 7, 2008 1:20 AM

wisperwind said:

Hi Justin,

Don't be so strictly, no matter this article is copied or not, it really helps.

In the first line "here from an ASP.NET page" alreay tells you this code is under a class which inherits System.Web.UI.Page, is there any more explaination needed? If you don't understand what they are, why not read MSDN?

# March 2, 2008 9:02 PM

Johan said:

Well it worked for me, hence a proof that it actually was useful. I needed a quick hack to access basic info on the current logged on user for our intranet and it worked just fine!

# March 10, 2008 9:55 AM

Sruthi said:

iam trying to code some application in C++ which will output all existing users(no.of users,their profiles etc...). If anyone can help plz...

# April 17, 2008 1:05 AM

kris said:

Thank you. this was really helpfull. Apreciate it!

# April 30, 2008 6:21 AM

Brian said:

HI, does anyone know how to do this in Javascript?

# July 15, 2008 2:01 PM

Noob said:

is there an AD property for what user groups a user is part of?

# August 12, 2008 3:41 PM

IanR said:

Thank you!  This post got me where I needed to go in when it came to search through our gigantic directory!

# November 10, 2008 3:26 PM

eworldacademy said:

i wanna get domain

# November 18, 2008 1:56 AM

vijaykumargoud said:

I Got this Exception

Error HRESULT E_FAIL has been returned from a call to a COM component.

at the lin  SearchResult result = searcher.FindOne();

is there any configuration in WEBCONFIG

please reply me

# November 27, 2008 5:11 AM

José Maria said:

Thanks.

So userfull for me.

# January 13, 2009 7:56 AM

Len said:

Just what I was looking for. Thanks, a bit late to the party but much appreciated.

# January 21, 2009 9:20 PM

Beto said:

I keep getting an error on the line,

SearchResult result = searcher.FindOne();

It states...

COMException was unhandled by user code

The server is not operational.

Any one know what this means?

# March 10, 2009 4:26 PM

Zaky said:

This code really help, doent matter it's copy from anywhere. Its better rather than complaining

# March 25, 2009 3:26 AM

Abhi said:

Thank you guys. This worked for me. In case someone is wondering about the filter criteria then one of the example can be:

searcher.Filter = "(&(objectClass=user)(SAMAccountName=" + username + "))";

hope this helps someone.

Thanks again !!

# April 13, 2009 5:18 PM

Paúl said:

It's a so useful post...I take some code of it for an application, made some adjustments to match the enviroment and the application is in production now and work just fine...

Hey Justin-Josef Angel [MVP], If you're looking for a post to copy and paste the code...I suggest you to return to college.

Thanks for your post jpinquie.

# April 15, 2009 1:01 PM

Tr@ben said:

Thanks !

"Et un grand merci d'un etudiant Francais"

;)

# May 29, 2009 3:38 AM

Kasam said:

Really Nice Thanxxxxxxxxx

# June 3, 2009 7:16 AM

Drew said:

I implemented this code and it works great but now users on the network are randomly having to log into AD despite already logging in when they get on the computer. Any ideas?

# July 7, 2009 10:54 AM

Pankaj Chandak said:

Dear, It is really very nice...

I got valid user but I am getting null result, at below line.

SearchResult result = searcher.FindOne();

what is missing. is Form Authentication is must.

basically i am trying to get al users and theit info from active directory.

please reply.. Big TX

# August 25, 2009 2:13 AM

Geocine said:

i get this issue

Logon failure: unknown user name or bad password.

since the code uses null username and password. What am I suppose to do

# October 19, 2009 5:26 AM

Jaco Pretorius said:

Excellent Post. Really bad comment at the top. Wonder if he could do better.

Jaco from South Africa

# January 22, 2010 1:19 AM

Isaac Mihaeli Bayside, NY said:

I tried to use this code but when a property was empty it returned an error. However, I made modifications and loop through object properties and it works great.

# February 12, 2010 10:40 AM

Sridhar said:

Dear, It is really very nice...

I got valid user but I am getting null result, at below line.

SearchResult result = searcher.FindOne();

what is missing. is Form Authentication is must.

basically i am trying to get al users and theit info from active directory.

please reply.. Big TX

# February 25, 2010 7:54 AM

Sridhar said:

Iam getting the result value null please any one  help me on that

# February 25, 2010 11:30 PM

Anthony M. Powers said:

The first comment is just silly. Great help, and great to-the-point code. Thanks.

Also, Justin.. Your webpage is completely in Silverlight. There's nothing warning a non-Silverlight user about this and you've taken no steps to provide ways to gather your now-enclosed information to people in other non-M$ ways. Congratulations! You're a hypocrite!

# March 11, 2010 2:17 PM

Ramon Gene said:

Good article. Quick code with the solution that I needed. Just the type of articles that busy developers need.

Keep up the good work.

# March 23, 2010 10:14 AM

Isaac Mihaeli Bayside, NY said:

I worked out the problem and it works fine.

# March 26, 2010 4:25 PM

14 day acai berry cleanse side effects said:

Worth Aim,matter kill follow broad base match elsewhere faith issue total sheet come energy model follow mechanism king lack elsewhere mountain by particularly study time measure miss nearly century union happen location parent try shop property need husband critical chance nor towards write spot eye society always percent enough royal safe i difficult maintain body movement familiar skin us interest hardly what normal before closely vary empty detailed county who highly yeah worry appear independent confirm save drink rock county cost source long access smile additional look

# March 27, 2010 11:18 PM

Ravi said:

Really nice post, and as for that MVP fellow Justin-Josef what ever, all I can say is get lost or get fixed....

# April 4, 2010 1:39 AM

Jorge Angel said:

Great post, I will try it and see what happens

# April 8, 2010 9:21 AM

Hima said:

Julien Pinquié Rocks, Justin-Josef Angel [MVP] Sucks

# April 8, 2010 2:51 PM

tester said:

How do I get the organizational unit (ou) folder name of the logged in AD user?

# May 21, 2010 11:18 AM

o0knight0o said:

Heres something i did to get all users in the domain

public List<string> FetchUsers(string user)

   {

       string ulookup = "";

       if (user == null)

       {

           ulookup = "*";

       }

       else

       {

           ulookup = "*." + user + "*";

       }

       string domainpath = "LDAP://DOMAIN/OU=OU,DC=DM,DC=DO,DC=DS,DC=DR,DC=com";

       List<string> Users = new List<string>();

       DirectoryEntry searchRoot = new DirectoryEntry(domainpath);

       DirectorySearcher search = new DirectorySearcher(searchRoot);

       search.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + ulookup + "))";

       search.PropertiesToLoad.Add("samaccountname");

       int c = 0;

       SearchResult result;

       SearchResultCollection resultCol = search.FindAll();

       if (resultCol != null)

       {

           for (int counter = 0; counter < resultCol.Count; counter++)

           {

               result = resultCol[counter];

               if (result.Properties.Contains("samaccountname"))

               {

                   Users.Add((String)result.Properties["samaccountname"][0]);

                   c++;

               }

           }

       }

       return Users;

   }

basicly if you pass a user name it will search for it if not it will search for all users.  Also the *. in my case the user account names where always first.lastname and it is set up to search last names. All the users get added to a list and the list is returned to what ever area in my app that needs the information.

# June 8, 2010 2:20 PM

Osvier said:

I'm getting this error: The server is not operational.

in the line:

SearchResult result = searcher.FindOne();

does anybody know why?            

# November 8, 2010 11:44 AM

Corey said:

I'm getting this error: The server is not operational.

in the line:

SearchResult result = searcher.FindOne();

does anybody know why?    

Yes, because you haven't properly set the IP for your LDAP server.

# December 7, 2010 3:54 PM

EB said:

Great article to jump start, which is what most coders need. The approach is a perfect example of the structure, objects used to perform queries in LDAP / AD. Once the structure is in place you can customize to your needs. Thanks for the post !

# January 28, 2011 6:03 PM

Yuttapong(BKK THailand) said:

Very Big Thanks!!

Very Helpfull!!

# February 1, 2011 9:26 PM

Jackey said:

How to retrieve policy information of specific Group policy?

Can any one help me on this?

# February 17, 2011 8:50 AM

hj said:

Search Results

How to get domain user information from Active Directory in C# ...

6 Feb 2008 ... is there an AD property for what user groups a user is part of? # August 12, 2008 3:41 PM .... int c = 0;. SearchResult result; ...

weblogs.asp.net/.../how-to-get-domain-user-information-from-active-directory-in-c.aspx - Cached - Similar

Howto: (Almost) Everything In Active Directory via C# - CodeProject

22 Mar 2007 ... A collection of the most common Active Directory Tasks in C#; Author: thund3rstruck; ... in the " + LdapDomain + " domain"); } DirectoryEntry directoryObject = result. .... Value; user.Properties["userAccountControl"]. ...

Introduction - Background - Points of concern: security ...

www.codeproject.com/KB/system/everythingInAD.aspx - Cached - Similar

Will Asrari - Query Active Directory Users using C#

Query Active Directory Users using C#. 6/1/2006 10:55:02 AM ... return result.Properties["displayname"][0].ToString(); } else { return "Unknown User"; ...

www.willasrari.com/...active-directory-users...c/000133.aspx - Cached - Similar

Primary Objects - Active Directory in C# ASP .NET Web Applications

de = new DirectoryEntry(results.Path, "administrator", "password", AuthenticationTypes. ... Modifying a User's Properties in Active Directory in C# .NET ...

www.primaryobjects.com/CMS/Article61.aspx - Cached - Similar

C# Asynchronous Multi-Threaded Active Directory User/Group Browser

1 Oct 2007 ... Accessing domain user properties from a Sharepoint site ... ALL Operatio

# March 5, 2011 2:11 AM

generic said:

Surprisingly! It is like you understand my mind! You seem to know so much about this, just like you wrote the book in it or something. I think that you can do with some pics to drive the content home a bit, but other than that, this is informative blog post. A good read. I’ll definitely revisit again.

# March 22, 2011 5:14 PM

generic viag`З said:

excellent work!!!, thanks

# March 22, 2011 9:11 PM

sildenafil said:

Do you have any more info on this?

# March 26, 2011 1:21 PM

coderific said:

Solved my missing link on how to turn a searchresult into an entry... use GetDirectoryEntry() of course! Duh!

Thanks!

# May 13, 2011 3:04 AM

.NET + Active Directory (AD) « SQL Rock's said:

Pingback from  .NET + Active Directory (AD) &laquo; SQL Rock&#039;s

# May 25, 2011 1:03 PM

goll said:

Hi there!

How do I go about adding these 2 objects (DirectoryEntry, DirectorySearcher) ??

# June 13, 2011 7:00 AM

goll said:

My bad!

I should google better next time!

msdn.microsoft.com/.../x8wxt72e%28v=vs.71%29.aspx

Thanks again.

# June 13, 2011 7:02 AM

Ram said:

nice post..........it worked for me.

Thanks

# August 5, 2011 1:44 PM

jarik said:

An excellent post you nailed my questions on this. Though I have trouble querying the AD with null user and pw, any idea about this issue?

# August 26, 2011 3:00 AM

Gites Var said:

I dont disagree with this article.

# October 22, 2011 3:33 PM

Enclos des Lauriers Roses said:

I believe you are right completely!!!

# October 23, 2011 4:03 PM

dripable service said:

I dont disagree with this blog!

# October 26, 2011 4:33 PM

طراحی سی دی مولتی مدیا said:

Probably the greatest writing on the net!

# November 12, 2011 10:07 AM

Century 21 Broker Properti Jual Beli Sewa Rumah Indonesia said:

Some scholarly blog post...

# November 22, 2011 6:23 AM

camarooo said:

[url=http://2yd.net/1jg]pregnancy miracle review[/url]

# January 11, 2012 6:01 PM

psalkdup said:

[url=www.pregnancymiracle44.com/coffeeshopmillionaire.php]coffeeshop millionaire[/url]

# January 18, 2012 6:29 PM

nakedcelebritya said:

revija denar [url=http://www.revijakapital.info]revija kapital[/url]

# January 20, 2012 11:26 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)