Reputation: 762
I'm trying to remove a certain user from an Active Directory group using C#. Here is my piece of code which should handle my task, even though it does not currently work.
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;
}
Please excuse me if there are any typos within this code, I had to manually copy it from the machine I am developing on, which has no internet access sadly.
Upvotes: 1
Views: 5556
Reputation: 89
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;
}
}
Upvotes: 0
Reputation:
Use:
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();
}
}
Upvotes: 2