C# 从Active Directory组中删除用户
我正在尝试使用C#从Active Directory组中删除某个用户。 这是我的一段代码,它应该处理我的任务,即使它目前不工作C# 从Active Directory组中删除用户,c#,active-directory,C#,Active Directory,我正在尝试使用C#从Active Directory组中删除某个用户。 这是我的一段代码,它应该处理我的任务,即使它目前不工作 public static bool RemoveUserFromGroup(string UserId, string GroupId) { using (var directory = new DirectoryEntry("LDAP://server")) { using (var dSearch = new DirectorySe
public static bool RemoveUserFromGroup(string UserId, string GroupId)
{
using (var directory = new DirectoryEntry("LDAP://server"))
{
using (var dSearch = new DirectorySearcher(directory))
{
try
{
dSearch.Filter = "(sAMAccountName=" + UserId + ")";
SearchResult sr = dSearch.FindOne();
System.DirectoryServices.PropertyCollection UserProperties = sr.GetDirectoryEntry().Properties;
if(UserProperties == null)
return false;
foreach(object Group in UserProperties["memberOf"])
{
if(Group.ToString() == GroupId)
{
UserProperties["memberOf"].Remove(GroupId);
directory.CommitChanges();
directory.Close();
return true;
}
}
}
catch (Exception e)
{
return false;
}
}
}
return false;
}
请原谅,如果这段代码中有任何拼写错误,我必须从我正在开发的机器上手动复制,这台机器无法访问互联网。:
我已经尝试使用此方法,但它对我不起作用。我得到消息“没有找到与指定参数匹配的主体”。当我进入debug mod时,我可以看到“Members”的计数抛出了一个异常,但是如果我单击“Result View”并展开结果,我会看到实际的组成员。尽管如此,我似乎无法访问它们。有什么想法吗?通过将“IdentityType.UserPrincipalName”切换到“IdentityType.SamAccountName”来绕过此错误。以上就是答案
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();
}
}
public string RemoveUserFromList(string UserID, string ListName)
{
try
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DomainName", UserName, Password))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, ListName);
group.Members.Remove(pc, IdentityType.SamAccountName, UserID);
group.Save();
}
return "Success";
}
catch (Exception ex)
{
return ex.Message;
}
}