Like I promised to give you a guick example of this 3.5 .net namespace . I will do so now
.
First make sure you have .net framwork 3.5 installed . Next fire up your 2005 or 2008 c# edition . Create a new project. Add a reference to System.DirectoryServices.Accountmanagement .
At this point on your form you can place a couple of controls on you form . A button , a listbox, textbox that you can enter a user or group name .

Make sure your controls are labled correctly (i.e txtUserName). And place this code in the click event of your button .
// Connect to Active directory with principlecontext
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "dcname");
This is just like doing a directory entry bind using directryentry(“LDAP:// ….. “)
So with this line your connected to your active directory .
The next bit of code is this :
//Create an instance of UserPriciple
UserPrincipal u = new UserPrincipal(ctx);
What we did here is create a new UserPrinciple instance and referenced ctx (our AD Domain )
The next code is kind of like a directorySearcher Class .
// Create an in-memory user object to use as the query example.
u = UserPrincipal.FindByIdentity(ctx, UserName);
We are taking the userprincipal variable and using the findbyIdentity method to find this usersname is AD . That is it you know have a full binding path to the User in AD . From here you can return the groups the user is a member of (Yes it will report back the primary Group as well )
Here is the complete code snippet :
// Connect to Active directory with principlecontext
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DCName");
//Create an instance of UserPriciple
UserPrincipal u = new UserPrincipal(ctx);// Create an in-memory user object to use as the query example.
u = UserPrincipal.FindByIdentity(ctx, UserName);
//Return a binding to the user
return u;
The reason why your seeing Return U is because I have this is an external Class and All I need to do is to call this and I’m connected to the user . Cool Huh ?
To get the groups a user is a member of you would do this .
PrincipalSearchResult Groups = u.GetGroups();
Use the PrincipalSearchResult to hold the results of the Groups .
There is also a GroupPrinciple Class to connect to a group the same way .
I hope this helps . A very nice Namespace !
Chris
Khaja Pasha 11:04 am on November 22, 2008 Permalink
Good help! thanks Chris..