How to find current user group from Active Directory

时间:2015-07-08 15:42:31

标签: c# active-directory

How to find current user group from Active Directory Server

refer screenshot url. http://i.stack.imgur.com/v1dww.png

For the username "palani", Group is Administrators.

How it can be get from Active Directory server

2 个答案:

答案 0 :(得分:0)

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find currently logged in user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "palani");

    if(user != null)
    {
         foreach(GroupPrincipal group in user.GetAuthorizationGroups().OfType<GroupPrincipal>())
         {
            Console.WriteLine("Group name: {0}", group.Name);
         }
    }
}

A user can be member of any number of groups - there isn't the group for a given user - there just is the list of groups he/she is a member of.

The new S.DS.AM makes it really easy to play around with users and groups in AD!

答案 1 :(得分:0)

你可以试试这个:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.com",
                                  "CN=palani,OU=Department,DC=domain,DC=com",
                                                             "administrator",
                                                                 "password");
        UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,"palani");
        if(usr!=null){
            Console.WriteLine(Convert.ToString(usr.SamAccountName));
            PrincipalSearchResult<Principal> group = usr.GetGroups();
            foreach(Principal pr in group)
                Console.WriteLine(pr.Name);
        }
        Console.Read();
相关问题