使用 C# 在 Active Directory 中创建新组并设置权限

Creating a new group and setting permissions in Active Directory using C#

我正在尝试构建一个在 Active Directory 中创建一些默认用户和组的应用程序。

我找到了这个代码,用于创建一个新组,但我不知道如何在生成后add/remove权限

这是我创建新群组的代码:

static void CreateNewSecutiryGroup(string ouPath, string name)
{
    try
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);

        DirectoryEntry group = entry.Children.Add("CN=" + name, "group");
        group.Properties["sAmAccountName"].Value = name;

        group.CommitChanges();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message.ToString());
    }
}

请帮忙,

谢谢。

这里是一些代码,展示了如何 1.) 通过 GetUser 获取用户对象,2.) 检查用户(或任何其他 DirectoryEntry,真的)是否已经是会员通过 IsGroupMember 和 3.) 通过 AddEntryToGroup.

将用户(或任何其他 DirectoryEntry)添加到组
private static DirectoryEntry GetUser(string withUserAccoutName, string inOUWithDNPath)
{
    var ouEntry = new DirectoryEntry(inOUWithDNPath);
    var searcher = new DirectorySearcher();
    searcher.SearchRoot = ouEntry;
    searcher.Filter = string.Format("(& (objectClass=User)(sAMAccountName={0}))", withUserAccoutName);
    var searchResults = searcher.FindAll();

    if (searchResults.Count > 0)
    {
        return searchResults[0].GetDirectoryEntry();
    }
    else
    {
        return null;
    }
}

private static bool IsGroupMember(DirectoryEntry entryToCheck, DirectoryEntry ofGroup)
{
    foreach (var memberPath in (IEnumerable) ofGroup.Invoke("Members", null))
    {
        var memberEntry = new DirectoryEntry(memberPath);

        if (((string) memberEntry.Properties["distinguishedName"].Value).Equals(((string) entryToCheck.Properties["distinguishedName"].Value), StringComparison.CurrentCultureIgnoreCase))
        {
            return true;
        }
    }

    return false;
}

private static void AddEntryToGroup(DirectoryEntry toAdd, DirectoryEntry toGroup)
{
    if (!IsGroupMember(toAdd, toGroup))
    {
        try
        {
            toGroup.Invoke("Add", new[] { toAdd.Path });
        }
        catch (Exception e)
        {
            throw e.InnerException; // unwrap the exception and throw that.
        }
    }
}