2010-07-01 31 views
10

我正在寻找一种方式来编程创建一个本地用户组。我发现了很多关于如何查询和添加用户的例子,但我无法理解如何创建一个新组。如何创建本地用户组(在C#中)

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

任何人都有一个代码片段,我可以用它来创建一个新的本地组?

回答

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文章改编。

它看起来像你错过了在你的例子中的调用“放” - 我想这就是为什么你看到NotImplementedException。

+0

是的,这正是发生了什么事。我找到了一个添加用户的例子,名为“Add”。与“Put”相同的代码现在可以运行。谢谢! – 2010-07-01 10:01:02

+0

没有足够的点票,但我已经接受了你的答案。 再次感谢。 – 2010-07-01 10:14:14

+0

@ the-diamond-z - 谢谢!我意识到我没有提出你的问题,所以我只是有。欢迎来到堆栈溢出! – 2010-07-01 10:19:47

6

你可以试试以下(还没有尝试过我自己):

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

这使用System.DirectoryServices.AccountManagement

+4

为什么你会发布答案,甚至没有尝试呢?这只是线路噪音,导致疯狂的追逐。 – 2010-07-13 15:16:37

+2

公平地说,它确实有效... – Doogal 2011-09-03 20:45:29

+0

您也可以在构造函数中传递组名,如下所示: GroupPrincipal group = new GroupPrincipal(context,“MyLocalGroup”) – 2012-06-02 04:10:41