你能在C#中发现的Active Directory用户的主要组? [英] Can you find an Active Directory User's Primary Group in C#?

查看:110
本文介绍了你能在C#中发现的Active Directory用户的主要组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作,管理用户帐户在Active Directory中的应用程序。我现在用的是System.DirectoryServices.AccountManagement命名空间徘徊无论有可能,但我不知道如何来确定用户的主要组。当我尝试删除一组是用户的主要组我得到一个异常。这是我目前的code:

I am working on an application that manages user accounts in Active Directory. I am using the System.DirectoryServices.AccountManagement namespace whereever possible, but I can't figure out how to determine a user's primary group. When I try to remove a group that is the user's primary group I get an exception. Here is my current code:

private void removeFromGroup(UserPrincipal userPrincipal, GroupPrincipal groupPrincipal) {
    TODO: Check to see if this Group is the user's primary group.
    groupPrincipal.Members.Remove(userPrincipal);
    groupPrincipal.Save();
}

有没有一种方法来获取用户的主组的名称,这样我就可以尝试从该组删除用户之前做一些验证?

Is there a way to get the name of the user's primary group so I can do some validation before trying to remove the user from this group?

推荐答案

这是一个相当混乱的,涉及的业务 - 但这code段是从我的海狸的ADSI浏览器,我用C#写的完全(在NET 1.1天),是众所周知的工作 - 不是pretty的,但功能:

It's quite a messy and involved business - but this code snippet is from my BeaverTail ADSI Browser which I wrote completely in C# (in the .NET 1.1 days) and is known to work - not pretty, but functional:

private string GetPrimaryGroup(DirectoryEntry aEntry, DirectoryEntry aDomainEntry)
{
   int primaryGroupID = (int)aEntry.Properties["primaryGroupID"].Value;
   byte[] objectSid = (byte[])aEntry.Properties["objectSid"].Value;

   StringBuilder escapedGroupSid = new StringBuilder();

   // Copy over everything but the last four bytes(sub-authority)
   // Doing so gives us the RID of the domain
   for(uint i = 0; i < objectSid.Length - 4; i++)
   {
      escapedGroupSid.AppendFormat("\\{0:x2}", objectSid[i]);
   }

   //Add the primaryGroupID to the escape string to build the SID of the primaryGroup
   for(uint i = 0; i < 4; i++)
   {
      escapedGroupSid.AppendFormat("\\{0:x2}", (primaryGroupID & 0xFF));
      primaryGroupID >>= 8;
   }

   //Search the directory for a group with this SID
   DirectorySearcher searcher = new DirectorySearcher();
   if(aDomainEntry != null)
   {
       searcher.SearchRoot = aDomainEntry;
   }

   searcher.Filter = "(&(objectCategory=Group)(objectSID=" + escapedGroupSid.ToString() + "))";
   searcher.PropertiesToLoad.Add("distinguishedName");

   return searcher.FindOne().Properties["distinguishedName"][0].ToString();
}

希望这有助于。

Hope this helps.

马克·

这篇关于你能在C#中发现的Active Directory用户的主要组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆