你能在 C# 中找到 Active Directory 用户的主要组吗?

时间:2022-11-10
本文介绍了你能在 C# 中找到 Active Directory 用户的主要组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在开发一个管理 Active Directory 中用户帐户的应用程序.我尽可能使用 System.DirectoryServices.AccountManagement 命名空间,但我不知道如何确定用户的主要组.当我尝试删除作为用户主要组的组时,出现异常.这是我当前的代码:

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?

推荐答案

这是一个相当混乱和复杂的业务 - 但这个代码片段来自我的 BeaverTail ADSI 浏览器,我完全用 C# 编写(在 .NET 1.1 时代)并且众所周知可以工作 - 不漂亮,但功能强大:

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();
}

希望这会有所帮助.

马克

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

上一篇:如何注册 System.DirectoryServices 以在 SQL CLR 用户函数中使用? 下一篇:获取给定 UserPrincipal 的组列表

相关文章

最新文章