How to create a local user group (in C#)
Asked Answered
P

2

10

I'm looking for a way how to programmatically create a local user group. I found plenty of examples on how to query and add users but nothing I can understand about how to create a new group.

var dirEntry = new DirectoryEntry(
                       "WinNT://" + Environment.MachineName + ",computer");

/* Code to test if the group already exists */            

if (!found)
{
    DirectoryEntry grp = dirEntry.Children.Add(groupName, "Group");
    dirEntry.CommitChanges();
}

This is what I've arrived at but I know it's wrong as CommitChanges() just throws a NotImplementedException.

I've been using this as a sample but I can't even get it to work (thanks MS):

http://msdn.microsoft.com/en-us/library/ms815734

Anyone have a code snippet I can use to create a new local group?

Parliamentary answered 1/7, 2010 at 9:32 Comment(0)
D
11

This works for me:

var ad = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
DirectoryEntry newGroup = ad.Children.Add("TestGroup1", "group");
newGroup.Invoke("Put", new object[] { "Description", "Test Group from .NET" });
newGroup.CommitChanges();

Adapted from this article on users.

It looks like you missed the Invoke "Put" in your example - I guess this is why you are seeing the NotImplementedException.

Doctrine answered 1/7, 2010 at 9:46 Comment(5)
Yep, that's exactly what happened. I found an example on adding a User and that called "Add". Same code with "Put" works now. Thanks!Parliamentary
Not enough points to vote, but I've accepted your answer. Thanks again.Parliamentary
@the-diamond-z - thanks! I realised I didn't upvote your question, so I just have. Welcome to Stack Overflow!Doctrine
And how to delete a group? Could maybe the "Delete" or "Remove" work? Could I find a documentation of these methods somewhere? Thank you. That'd help a lot!Crutchfield
Note: DirectoryEntry is disposable.Squib
K
7

You may try the following (haven't tried it myself):

PrincipalContext context = new PrincipalContext(ContextType.Machine);
GroupPrincipal group = new GroupPrincipal(context);
group.Name = model.Name;
group.Save();

This uses System.DirectoryServices.AccountManagement.

Kampmeier answered 1/7, 2010 at 9:47 Comment(2)
Why would you post an answer without even trying it? It's just line noise that leads to wild goose chases.Weimer
You can also pass the group name in the constructor as in: GroupPrincipal group = new GroupPrincipal(context, "MyLocalGroup")Feat

© 2022 - 2024 — McMap. All rights reserved.