问题描述
我正在编写以下方法来在 C# 中从活动目录中添加和删除用户.
I am writing the following methods to add and remove users from active directory in C#.
void AddUserToGroup(string userId, string groupName);
void RemoveUserFromGroup(string userId, string groupName);
如何最好地实现这些方法?
How best to implement these methods?
这是来自 CodeProject 的一些代码.我看不到在这些示例中指定 AD 服务器的位置吗?(在使用 LDAP 协议时,它是由 .NET 框架隐式提供的吗?).这些例子值得学习吗?
Here is some code from CodeProject. I can't see where the AD server is specified in these examples though? (is it implicitly supplied by the .NET framework when using the LDAP protocol?). Are these examples worth following?
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();
}
}
推荐答案
呃.LDAP.如果您使用的是 .Net Framework 3.5 或更高版本,我强烈建议您使用 System.DirectoryServices.AccountManagement 命名空间.这让事情如此变得容易多了.
Ugh. LDAP. If you're using the .Net Framework 3.5 or above, I highly recommend using the System.DirectoryServices.AccountManagement namespace. That makes things so much easier.
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();
}
}
这篇关于在 .NET 中的 Active Directory 组中添加和删除用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!