如何创建本地用户组(C#)

发布于 2024-09-08 07:08:01 字数 686 浏览 9 评论 0原文

我正在寻找一种以编程方式创建本地用户组的方法。我找到了大量有关如何查询和添加用户的示例,但我无法理解如何创建新组。

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏末 2024-09-15 07:08:01

这对我有用:

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 的原因。

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.

太阳公公是暖光 2024-09-15 07:08:01

您可以尝试以下操作(我自己没有尝试过):

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

这使用 System.DirectoryServices.AccountManagement

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文