使用C#向Active Directory组添加用户时遇到问题

3

好的,我现在的问题是我们正在试图编写代码,将用户添加到我们的活动目录中的另一个组中。这是我们编写的解决方案。

主方法的一部分:

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))
at System.DirectoryServices.DirectoryEntry.InvokeSet(String propertyName, Object[] args)
at adjustUsers.Program.AddToGroup(String userDn, String groupDn) in C:\Users\XXX\Documents\Visual Studio 2010\Projects\UserPruning\adjustUsers\Program.cs:line 45
at UserPruning.MainProgram.Main(String[] args) in C:\Users\XXX\Documents\Visual Studio 2010\Projects\UserPruning\UserPruning\MainProgram.cs:line 46

根据我们的调查,这通常表示语法存在问题。

第46行是:

string adduser = ad.AddToGroup(userName,newGroup)

第45行是

ldapConnection.Invoke("Add", new object[] {newUser});

我们已经尝试重写这段代码一整天了,但仍然束手无策。

可以帮忙吗?

谢谢。

1个回答

8
如果您在使用.NET 3.5及以上版本,建议您查看System.DirectoryServices.AccountManagement (S.DS.AM)命名空间。在此处阅读相关信息: 基本上,您可以定义一个域上下文,并轻松地在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中玩弄用户和组变得非常容易!

2
我希望我可以多次点赞这个答案。我觉得我在网上找到的关于使用C#进行AD操作的几乎所有内容都链接到了"Howto: (Almost) Everything in Active Directory via C#" [http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C] 这篇文章,该文章使用了DirectoryEntry API。而DirectoryServices API则更加优秀!非常感谢! - Dan Forbes
问题在于,如果运行AccountManagement命名空间的计算机不在该域上并且无法解析您正在查询的域,则它将无法正常工作。 - EndOfAll
我正在查询另一个域,这可能是导致异常“无法检索有关该域的信息(1355)”的原因吗? - vbhosale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接