Can you find an Active Directory User#39;s Primary Group in C#?(你能在 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 用户的主要组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你能在 C# 中找到 Active Directory 用户的主要组吗
基础教程推荐
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- 创建属性设置器委托 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01