新建一个控制台应用程序,添加引用:System.DirectoryServices
定义参数:
private static string ADPassword ="xxxxxx";
private static string ADPath = "LDAP://xxx.com";
private static string ADUser ="xxxxxx";
private static AuthenticationTypes DefaultAuthenticationType = AuthenticationTypes.Secure;
//得到根目录下的OU
public static SearchResultCollection GetRootOus()
{
try
{
DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, DefaultAuthenticationType);
DirectorySearcher directorySearch = new DirectorySearcher(entry);
directorySearch.Filter = "(&(objectClass=organizationalUnit))";
directorySearch.SearchScope = SearchScope.OneLevel;
SearchResultCollection results = directorySearch.FindAll();
if (results != null)
{
return results;
}
else
{
return null;
}
}
catch (Exception ex)
{
Log.CreateLogManager().Error("方法:ADHelper.GetRootOus方法执行失败",ex);
return null;
}
}
获取OU和OU下的用户:
try
{
DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, DefaultAuthenticationType);
DirectorySearcher directorySearch = new DirectorySearcher(entry);
directorySearch.Filter = "(&(objectClass=organizationalUnit))";
directorySearch.SearchScope = SearchScope.OneLevel;
SearchResultCollection results = directorySearch.FindAll();
if (results != null)
{
foreach (System.DirectoryServices.SearchResult item in results)
{
DirectoryEntry OUResults = item.GetDirectoryEntry();
if (OUResults.Properties.Contains("ou") && OUResults.Properties.Contains("objectGUID"))// Search OU
{
string rootOuName = OUResults.Properties["ou"][0].ToString();
byte[] bGUID = OUResults.Properties["objectGUID"][0] as byte[];
string id = BitConverter.ToString(bGUID);
Console.WriteLine(id);
Console.WriteLine(rootOuName);
DirectoryEntry ou = entry.Children.Find("OU=" + rootOuName);//Search Users Under the OU
DirectorySearcher mySearcher = new DirectorySearcher(ou);//想搜索出所有,此处可省参数
mySearcher.Filter = ("(objectClass=user)"); //user表示用户,group表示组
var users = mySearcher.FindAll();
foreach (System.DirectoryServices.SearchResult usersitem in users)
{
DirectoryEntry user = usersitem.GetDirectoryEntry();
//if (user.Properties.Contains("Name"))
//{
// string Name = user.Properties["Name"][0].ToString();
// Console.WriteLine(Name);
//}
if (user.Properties.Contains("sAMAccountName"))
{
string sAMAccountName = user.Properties["sAMAccountName"][0].ToString();
Console.WriteLine(sAMAccountName);
}
user.Close();
user.Dispose();
}
ou.Close();
ou.Dispose();
}
OUResults.Close();
OUResults.Dispose();
}
}
entry.Close();
entry.Dispose();
}
catch (Exception ex)
{
throw;
}