System.DirectoryServices.AccountManagement namespace

The AccountManagement namespace is part of the .Net 3.5 framework, and provides an easy way to access and modify directory services.

I used to have my own ADHelper library that encapsulated the methods in System.DirectoryServices namespace.

Recently, i had to find out if a user was member of a specified group. This was possible, but it took a lot of lines of code. With the AccountManagement namespace it can be done in a few lines:

    static void Main()

    {

       UserPrincipal user = UserPrincipal.Current;

       if (user == null && !IsMemberOf(user, Settings.Default.EditorRole))

       {

         // user is found

       }

    }

 

    static bool IsMemberOf(UserPrincipal user, string roleName)

    {

        bool result = false;

        if (user != null)

        {

            PrincipalSearchResult groups = user.GetGroups();

            if (groups != null)

            {

                foreach (Principal principal in groups)

                {

                    if (principal.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase))

                    {

                        result = true;

                        break;

                    }

                }

            }

        }

        return result;

    } 

Comments

One response to “System.DirectoryServices.AccountManagement namespace”

  1. Dennis Avatar

    Thanks for the code sample. This was very useful in understanding and putting into practice the AD integration in .Net.
    Marc Sirois
    Ottawa, Canada

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.