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

时间:2015-07-07 11:17:16

标签: c# permissions active-directory ldap directoryservices

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

我设法找到了这个代码,用于创建一个新组,但我不知道如何在生成后添加/删除该组的权限。

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

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 个答案:

答案 0 :(得分:1)

以下是一些代码,说明如何1.)通过GetUser获取用户对象,2。)检查用户(或任何其他DirectoryEntry)是否已经是通过IsGroupMember分组,以及3.)通过DirectoryEntry将用户(或任何其他AddEntryToGroup)添加到组中。

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.
        }
    }
}