Getting Exception trying to delete a Local User Group using Directory Services Account Management in C#

1k views Asked by At

I'm trying to programmatically delete a local user group. I'm using the following code which I've cobbled together from various examples online. From everything I've read, it should work. But the Delete line throws an exception.

PrincipalContext context = new PrincipalContext( ContextType.Machine );
GroupPrincipal group = new GroupPrincipal( context );
PrincipalSearcher ps = new PrincipalSearcher( group );
PrincipalSearchResult<Principal> results = ps.FindAll();
Principal foundGroup = results.SingleOrDefault( item => item.Name == groupName );
if(foundGroup != null)
    foundGroup.Delete(); // Here occurs the InvalidOperationException

This throws an InvalidOperationException with the message:

The Active Directory object located at the path WinNT://LOREM/IPSUM is not a container."

I'm a complete newbie when it comes to this Active Directory stuff.

2

There are 2 answers

1
MichelZ On

Can you try PrincipalSearchResult<GroupPrincipal>?

I am also not sure if your .SingleOrDefault is used correctly. Can you try:

results.Where(item => item.Name == groupName).SingleOrDefault();
0
Nathan Sosnovske On

This was asked a while ago, but I ran into this issue today. It seems that there is a bug in the Group and UserPrincipal library. This is how I worked around it for anyone who runs into this in the future:

For groups:

string groupName = "myGroup";

// Workaround: WinNT://DOMAIN/USER is not a container even if group is empty
using (var root = new DirectoryEntry($"WinNT://{Environment.MachineName}"))
using (var group = root.Children.Find(groupName, "group"))
{
    root.Children.Remove(group);
    result = true;
}

For user accounts:

string userAccountName = "myUser";

// Workaround: WinNT://DOMAIN/USER is not a container issue
using (var root = new DirectoryEntry($"WinNT://{Environment.MachineName}"))
using (var userAccount = root.Children.Find(userAccountName))
{
    root.Children.Remove(userAccount);
}