Add user to group - Active Directory
I wanted to add a user to group .
But its throwing error like “Exception has been thrown by the target of an invocation.”
anybody has any idea why it is?
this is my code
public static void AddUserToGroup()
{
string sDomainName =
"LDAP://ADServer/DC=ADServer,DC=tech";
ActiveDirectoryAccess objAD = new
ActiveDirectoryAccess(sDomainName);
DirectoryEntry de = new
DirectoryEntry(sDomainName);
DirectoryEntry deUser =
objAD.GetDirectoryUserEntry("anurag");
string GroupName = "Now";
DirectorySearcher deSearch = new
DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=group)
(cn=" + GroupName + "))";
SearchResultCollection results =
deSearch.FindAll();
bool isGroupMember = false;
if (results.Count > 0)
{
DirectoryEntry group =
objAD.GetDirectoryGroupEntry(results[0].Path);
object members =
group.Invoke("Members", null);
foreach (object member in
(IEnumerable)members)
{
DirectoryEntry x = new
DirectoryEntry(member);
if (x.Name != deUser.Name)
{
isGroupMember = false;
}
else
{
isGroupMember = true;
break;
}
}
if (!isGroupMember)
{
group.Invoke("Add", new object[] {
deUser.Path.ToString() });
}
group.Close();
}
return;
}
Rgs,
Anurag
|