简体   繁体   English

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

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

I'm trying to build an app that creates some default users and groups in Active Directory. 我正在尝试构建一个在Active Directory中创建一些默认用户和组的应用程序。

I've managed to find this code, for creating a new group, but I don't know how to add/remove permission to the group after being generated. 我设法找到了用于创建新组的代码,但是在生成后我不知道如何向该组添加/删除权限。

This is my code for creating a new group: 这是我用于创建新组的代码:

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());
    }
}

Please help, 请帮忙,

thank you. 谢谢。

Here is some code which shows how to 1.) obtain a user object via GetUser , 2.) check if the user (or any other DirectoryEntry , really) is already a member of the group via IsGroupMember , and 3.) add the user (or any other DirectoryEntry ) to the a group via AddEntryToGroup . 下面是一些代码,其显示了如何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.
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM