51

C#のActive Directoryにユーザーを追加したり、アクティブディレクトリからユーザーを削除したりするために、次のメソッドを作成しています。

void AddUserToGroup(string userId, string groupName);
void RemoveUserFromGroup(string userId, string groupName);

これらのメソッドを実装するのに最適な方法は?

これがCodeProjectのコードです。これらの例でADサーバーが指定されている場所がわかりませんが?(LDAPプロトコルを使用する場合、.NET Frameworkによって暗黙的に提供されますか?)これらの例はフォローする価値がありますか?

public void AddToGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Properties["member"].Add(userDn);
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();

    }
}


public void RemoveUserFromGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Properties["member"].Remove(userDn);
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();

    }
}
4

4 に答える 4

97

うーん。LDAP。.Net Framework 3.5以降を使用している場合は、System.DirectoryServices.AccountManagement名前空間を使用することを強くお勧めします。それは物事をとても簡単にします。

public void AddUserToGroup(string userId, string groupName) 
{ 
    try 
    { 
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "COMPANY"))
        {
            GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
            group.Members.Add(pc, IdentityType.UserPrincipalName, userId);
            group.Save();
        }
    } 
    catch (System.DirectoryServices.DirectoryServicesCOMException E) 
    { 
        //doSomething with E.Message.ToString(); 

    } 
} 

public void RemoveUserFromGroup(string userId, string groupName)
{   
    try 
    { 
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "COMPANY"))
        {
            GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
            group.Members.Remove(pc, IdentityType.UserPrincipalName, userId);
            group.Save();
        }
    } 
    catch (System.DirectoryServices.DirectoryServicesCOMException E) 
    { 
        //doSomething with E.Message.ToString(); 

    }
}
于 2010-01-27T00:26:22.223 に答える
4

サーバーはgroupDn変数値の一部です。例えば:

LDAP://myServer/CN=MyGroup,CN=Groups,CN=MyContainer,DN=mydomain.com

すべては、グループのLDAPパスです。最初の部分(myServer)はサーバー名です。

サーバー名(CN = ...など)の後の部分は、グループのDN(識別名)です。

于 2010-01-26T22:15:23.330 に答える
3

でメンバーを削除する場合 public void RemoveUserFromGroup(string userDn, string groupDn)

dirEntry.Properties["member"].Remove(userDn)私にはうまくいきません。

dirEntry.Properties["member"].RemoveAt(dn.IndexOf(dn))動作します。

于 2012-01-26T09:36:34.720 に答える
1

LDAPサーバーをDirectoryEntryへのパス引数に入れることができるので、「LDAP://」+ ldapServer+ldapQueryです。

認証が必要な場合は、DirectoryEntry(文字列パス、文字列userId、文字列パスワード)を使用します

于 2010-01-26T22:16:17.077 に答える