Active directory LDAP:如何向OU内的组添加新用户

Active directory LDAP:如何向OU内的组添加新用户,active-directory,ldap,directoryentry,Active Directory,Ldap,Directoryentry,我有一些代码使用DirectoryEntry通过LDAP操作本地Active Directory。目前,我找到一个特定的OU,向其中添加一个用户,更新该用户的属性,然后提交所有更改: DirectoryEntry ldapRoot = new DirectoryEntry(ldapString, user, password); DirectoryEntry userGroup = ldapRoot.Children.Find("OU=OUGroup"); DirectoryEntry newU

我有一些代码使用
DirectoryEntry
通过LDAP操作本地Active Directory。目前,我找到一个特定的
OU
,向其中添加一个用户,更新该用户的属性,然后提交所有更改:

DirectoryEntry ldapRoot = new DirectoryEntry(ldapString, user, password);
DirectoryEntry userGroup = ldapRoot.Children.Find("OU=OUGroup");
DirectoryEntry newUser = userGroup.Children.Add("CN=" + userName, "user");
newUser.Properties["displayName"].Value = displayName;

...

newUser.CommitChanges();
userGroup.Close();
ldapRoot.Close();
ldapString类似于LDAP:\\DC=company,DC=local,基本上它只是获取根条目

我改变了几个属性,但一切正常。但是,我有另一个
OU
名为SharePoint\u Groups,其中有一个名为
Internal
的组。我想将新用户添加为此组的成员,但我不知道如何添加。我尝试了以下方法:

DirectoryEntry spGroup = ldapRoot.Children.Find("OU=Sharepoint_Groups");
DirectoryEntry internal = spGroup.Children.Find("CN=Internal");
它不起作用,我不确定应该如何处理
内部
-CN=正确吗,还是应该使用其他规范

而且,一旦我拥有了正确的组,如何将现有用户添加到该组中


提前感谢

基本上,要将用户添加到现有组,您需要绑定到该组并使用用户的完全限定可分辨名称更新其
成员
属性:

DirectoryEntry deGroup = new DirectoryEntry("LDAP://CN=Internal,OU=Sharepoint_Groups,DC=Company,DC=local");

string userDN = newUser.Properties["distinguishedName"][0].ToString();

deGroup.Properties["member"].Add(userDN);
deGroup.CommitChanges();

CodeProject文章是这类文章的一个很好的参考资料——许多有用的代码示例

工作非常完美,似乎在执行Add()时出错了,因为我只使用了“CN=username”而不是完整的DN。谢谢知道为什么这在本地工作,但在移动到IIS服务器时抛出“访问被拒绝”吗?@PlatypusMaximus:听起来像是权限-在本地,此代码在您自己的用户的上下文中运行-在web上,最有可能在IIS的应用程序池用户的上下文中运行