使用C#将用户添加到Active Directory组时出现问题
本文关键字:问题 Directory Active 用户 添加 使用 | 更新日期: 2023-09-27 17:58:09
好吧,我现在的问题是,我们正试图编写代码,将用户添加到Active Directory中的另一个组中。这就是我们编写的解决方案。
主要方法的一部分:
string newGroup = "TestDelete";
string userName = result.Properties["cn"][0].ToString();
string adduser = ad.AddToGroup(userName, newGroup);
Console.WriteLine(String.Format("{0} : {1}",userName, adduser));
它从另一个类调用此方法:
public String AddToGroup(string userDn, string groupDn)
{
try
{
DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://OU=" + groupDn + ",DC=blah,DC=blah,DC=blah");
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
string newUser = "CN=" + userDn + "CN=Members,DC=blah,DC=blah,DC=blah";
ldapConnection.Invoke("Add", new object[] { newUser });
ldapConnection.CommitChanges();
ldapConnection.Close();
return "Success";
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
Console.WriteLine("Exception caught:'n'n" + E.ToString());
}
}
它抛出了异常
System.Runtime.InteropServices.COMException(0x80020006):未知名称。(HRESULT中的异常:0x80020006(DISP_E_UNKNOWNNAME))
位于System.DirectoryServices.DirectoryEntry.InvokeSet(字符串属性名称,对象[]参数)
在C:''Users''XXX''Documents''Visual Studio 2010''Projects''UserPruning''adjustUsers''Program.cs:line 45
中的adjustUsers.Program.AddToGroup(字符串用户Dn,字符串组Dn)位于C:''Users''XXX''Documents''Visual Studio 2010''Projects''UserPrunning''UserPruning''MainProgram.cs:line 46中的UserPruning.MainProgram.Main(String[]args)
据我们所知,这表明我们的语法有问题。
第46行为
string adduser = ad.AddToGroup(userName,newGroup)
第45行为
ldapConnection.Invoke("Add", new object[] {newUser});
我们在最后一天一直试图重写这段代码,但仍然被难住了。
帮助?
感谢
如果您使用的是.NET 3.5及更高版本,则应该检查System.DirectoryServices.AccountManagement
(S.DS-AM)命名空间。点击此处阅读:
- 在.NET Framework 3.5中管理目录安全主体
- System.DirectoryServices.AccountManagement上的MSDN文档
基本上,您可以定义域上下文,并在AD:中轻松找到用户和/或组
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "TestDelete");
// if found....
if (group != null)
{
// add user to group
group.Members.Add(user);
group.Save();
}
}
}
新的S.DS.AM让在AD中与用户和组一起玩变得非常容易!