AccountManagment in .NET 3.5#

I can’t believe it took this long to get a better way to manage users and groups through code!

There is a new namespace in .NET 3.5 System.DirectoryServices.AccountManagement which allows easy management of users and groups via code.

Below shows how easy it is to get the local IIS_WPG group:

 PrincipalContext context = new PrincipalContext(ContextType.Machine);
 GroupPrincipal iisWpgGroup = GroupPrincipal.FindByIdentity(context, IdentityType.Name, "IIS_WPG")

It used to difficult to even find if a user was a member of a group.  Now there is a “Contains” on the group and there is also LINQ which is what I used.

var addedUser = iisWpgGroup.Members.SingleOrDefault(principal => principal.SamAccountName == "User1");

The above will return the member if they are there or null if the member is not in the group.  It is also stupid simple to add and remove members from a group.

Add Local:

iisWpgGroup.Members.Add(context, IdentityType.Name, “User1”);

iisWpgGroup.Save();

Add Domain:

PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain);
iisWpgGroup.Members.Add(domainContext, IdentityType.SamAccountName, “User1”);

iisWpgGroup.Save();

Remove:

var user = iisWpgGroup.Members.SingleOrDefault(p => p.SamAccountName == “User1”);
if (user != null)
{
       iisWpgGroup.Members.Remove(user);
       iisWpgGroup.Save();
}

Tuesday, December 04, 2007 5:16:07 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview
All content © 2009, John Luif