10

我正在寻找一种如何以编程方式创建本地用户组的方法。我发现了很多关于如何查询和添加用户的示例,但我对如何创建新组一无所知。

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();
}

这就是我所达到的,但我知道这是错误的,因为CommitChanges()只是抛出一个NotImplementedException.

我一直在使用它作为示例,但我什至无法让它工作(感谢 MS):

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

有人有我可以用来创建新本地组的代码片段吗?

4

2 回答 2

10

这对我有用:

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();

改编自这篇关于用户的文章。

看起来您在示例中错过了 Invoke “Put” - 我想这就是您看到 NotImplementedException 的原因。

于 2010-07-01T09:46:30.313 回答
7

您可以尝试以下方法(自己没有尝试过):

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

这使用System.DirectoryServices.AccountManagement.

于 2010-07-01T09:47:10.763 回答