【问题标题】:Creating a new group and setting permissions in Active Directory using C#使用 C# 在 Active Directory 中创建新组并设置权限
【发布时间】:2015-09-24 20:30:23
【问题描述】:

我正在尝试构建一个在 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());
    }
}

请帮忙,

谢谢。

【问题讨论】:

    标签: c# permissions active-directory ldap directoryservices


    【解决方案1】:

    这里有一些代码显示如何 1.) 通过GetUser 获取用户对象,2.) 通过@987654323 检查用户(或任何其他DirectoryEntry,真的)是否已经是组的成员@ 和 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.
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多