我正在寻找一种如何以编程方式创建本地用户组的方法。我发现了大量关于如何查询和添加用户的示例,但我无法理解如何创建新组。
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
任何人都有可用于创建新本地群组的代码段吗?
答案 0 :(得分: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();
改编自this关于用户的文章。
看起来您错过了示例中的Invoke“Put” - 我想这就是您看到NotImplementedException的原因。
答案 1 :(得分:7)
您可以尝试以下方法(我自己没试过):
PrincipalContext context = new PrincipalContext(ContextType.Machine);
GroupPrincipal group = new GroupPrincipal(context);
group.Name = model.Name;
group.Save();