0

I'm trying to build an app that creates some default users and groups in 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.

1 Answer 1

1

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.

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.
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.