使用C#将用户添加到Active Directory组时出现问题

Kat*_*ger 2 c# directoryservices active-directory active-directory-group windows-server-2008-r2

好的,我现在的问题是我们正在尝试编写将用户添加到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)); 
Run Code Online (Sandbox Code Playgroud)

哪个从另一个类调用此方法:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

它抛出异常

System.Runtime.InteropServices.COMException(0x80020006):未知名称.(来自HRESULT的异常:0x80020006(DISP_E_UNKNOWNNAME))
System.DirectoryServices.DirectoryEntry.InvokeSet(String propertyName,Object [] args)
at C:\ Users\XXX\Documents \中的adjustUsers.Program.AddToGroup(String userDn,String groupDn) Visual Studio 2010\Projects\UserPruning\adjustUsers\Program.cs:
位于C:\ Users\XXX\Documents\Visual Studio 2010\Projects\UserPruning\UserPruning\MainProgram中的UserPruning.MainProgram.Main(String [] args)的第45行. cs:第46行

据我们所能找到的,表明我们的语法存在问题.

第46行是

string adduser = ad.AddToGroup(userName,newGroup)
Run Code Online (Sandbox Code Playgroud)

第45行是

ldapConnection.Invoke("Add", new object[] {newUser});
Run Code Online (Sandbox Code Playgroud)

我们一直试图在最后一天重写这段代码,但仍然难倒.

救命?

谢谢

mar*_*c_s 5

如果您使用的是.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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

新的S.DS.AM使得在AD中与用户和群组玩游戏变得非常容易!

  • 我希望我能不止一次地对这个答案进行投票。我觉得我在网上找到的关于通过 C# 进行 AD 操作的几乎所有内容都链接到 Howto:(几乎) Active Directory 中的所有内容通过 C# [http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In -Active-Directory-via-C] 文章,它使用 DirectoryEntry API。DirectoryServices API 更好了!非常感谢! (2认同)