пятница, 15 октября 2010 г.

Получение пользователей из AD на C#

using System;
using System.DirectoryServices;
using System.Collections;
using System.Linq;
using System.IO;

class Program
{

static void Main(string[] args)
{
DirectoryEntry de = new DirectoryEntry("LDAP://"+serverName, userName, password);
DirectorySearcher deSearch = new DirectorySearcher();

deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user))";
deSearch.SearchScope = SearchScope.Subtree;

SearchResultCollection results = deSearch.FindAll();

foreach (SearchResult result in results)
{
DirectoryEntry entity = result.GetDirectoryEntry();

if ((entity.SchemaEntry.Name == "user") && (entity.Name.IndexOf("CN=") != -1))
{
Console.Write(entity.Name.Substring(3) + "\n");
}
}
}
}