Ben*_*Ben 42 .net c# ldap active-directory active-directory-group
我正在编写以下方法来在C#中添加和删除活动目录中的用户.
void AddUserToGroup(string userId, string groupName);
void RemoveUserFromGroup(string userId, string groupName);
Run Code Online (Sandbox Code Playgroud)
如何最好地实现这些方法?
以下是CodeProject的一些代码.我在这些示例中看不到AD服务器的位置?(在使用LDAP协议时,它是由.NET框架隐式提供的吗?).这些例子值得关注吗?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
Jac*_*itt 81
啊.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();
}
}
Run Code Online (Sandbox Code Playgroud)
服务器是groupDn变量值的一部分。例如:
LDAP://myServer/CN=MyGroup,CN=Groups,CN=MyContainer,DN=mydomain.com
整个内容就是组的 LDAP 路径。第一部分 (myServer) 是服务器名称。
服务器名称后面的部分(例如 CN=...)是组的 DN(可分辨名称)。
归档时间: |
|
查看次数: |
74765 次 |
最近记录: |