Click here to Skip to main content
16,022,297 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I've a c# console application that is meant to be used to add/remove computer accounts from certain groups and the application works properly, except for a small "but". It adds/removes the relevant computer to/from the relevant AD group, but even if the computer is already member of the group or if it already has been removed no exception is thrown.

This is my code:

C#
try
{
    string strDC = GetDomainController(strOldDAGroupDN.Substring(strOldDAGroupDN.IndexOf("DC")).Replace("DC=", "").Replace(",", ".").Replace("}", ""));
    DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + strDC + "/" + strOldDAGroupDN);
    dirEntry.Username = strEntAdminUser;
    dirEntry.Password = strEntAdminPW;
    dirEntry.Properties["member"].Remove(strHostDN);
    dirEntry.CommitChanges();
    dirEntry.Close();
}
catch (Exception e)
{
    TextWriter errorWriter = Console.Error;
    errorWriter.WriteLine("Error while removing computer account to AD group!");
    errorWriter.WriteLine(e.Message);
}

When I start debugging and go through the code line, by line, the CommitChanges() call should throw an exception but it doesn't.

What am I doing wrong?

Thanks in advance!

Best,
Markus

What I have tried:

Initially the add/remove computer to group parts were not directly in the main code itself but in functions, but this didn't work either.
Posted
Comments
Richard Deeming 5-Jul-24 9:20am    
Why do you think it should throw an exception?

CommitChanges is not documented as throwing any exceptions. And the PropertyValueCollection.Add/Remove methods are only documented as throwing an exception if the value is null or there is an error calling the underlying COM interface.

So where have you seen any documentation saying that your code should throw an exception?
thomas1803 8-Jul-24 2:58am    
You can improve your code to handle the scenario where the computer account is already a member or not found by checking Membership Before Modification. Buildnow GG

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900