[英]Creating a new group and setting permissions in Active Directory using C#
我正在嘗試構建一個在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)獲得通過用戶對象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.