And*_*May 5 c# active-directory c#-3.0
我正在开发一个管理Active Directory中的用户帐户的应用程序.我尽可能使用System.DirectoryServices.AccountManagement命名空间,但我无法弄清楚如何确定用户的主要组.当我尝试删除作为用户主要组的组时,我得到一个例外.这是我目前的代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法获取用户的主要组的名称,以便我可以在尝试从该组中删除用户之前进行一些验证?
这是一个非常混乱和涉及的业务 - 但这段代码片段来自我的BeaverTail ADSI浏览器,我完全用C#编写(在.NET 1.1天内)并且已知可以工作 - 不漂亮但功能性:
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();
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
渣
小智 0
用户主要组的 RID 存储在用户对象的“primaryGroupID”属性中。您必须获取给定用户(或用户其他 API)的 DirectoryEntry 才能检索此值。获取该值后,您必须将其转换为主要组的 SID,然后从中获取组。
有一篇知识库文章对此有更多详细信息,以及有关如何查找主要组的 VB 代码,此处:http ://support.microsoft.com/kb/297951
归档时间: |
|
查看次数: |
7188 次 |
最近记录: |