DirectorySearcher 类介绍
1.作用:
对 Active Directory 执行查询。
2。备注
使用轻量目录访问协议 (LDAP) 并使用 DirectorySearcher 对 Active Directory 层次结构进行搜索和执行查询。LDAP 是系统提供的唯一支持目录搜索的 Active Directory 服务接口 (ADSI) 提供程序。管理员可以创建、更改和删除在层次结构中找到的对象。有关更多信息,请参见“Visual Studio.NET 中的 Active Directory 对象简介”。

在创建 DirectorySearcher 的实例时,通过 SearchRoot 属性指定要检索的根目录和要检索的可选的属性列表。还可以设置属性以确定:
(1) 是否要在本地计算机上缓存搜索结果。将 CacheResults 属性设置为 true,以在本地计算机上存储目录信息。只有在调用 DirectoryEntry.CommitChanges 方法时,才对此本地缓存进行更新,并提交到 Active Directory。
(2) 在搜索上要花费的时间。使用 ServerTimeLimit 属性指定搜索可持续的时间长度。
(3) 是否只检索属性名称。将 PropertyNamesOnly 属性设置为 true,就会只检索已经为其赋值的属性的名称。
(4) 是否执行分页搜索。设置 PageSize 属性,以指定在分页搜索中返回的最大对象数。如果不想执行分页搜索,请将 PageSize 属性设置为其默认值零。
(5) 要返回的项的最大数量。设置 SizeLimit 属性以指定要返回的项的最大数量。若将 SizeLimit 属性设置为其默认值零,则会将它设置为服务器确定的默认值 1000 项。
    注意   如果返回的项的最大数量和时间限制超过服务器上设置的限制,则服务器设置覆盖组件设置。
3. 示例:

 下面的代码演示了一个如何类,其中包括一个GetUserList方法,用来获得当前DirectoryEntry下面的用户列表:
-----------------------------------------------------------------------------------------------------

// Disclaimer and Copyright Information
// ADSIUtil.aspx.cs :
//
// All rights reserved.
//
// Written by Pardesi Services, LLC
// Version 1.0
//
// Distribute freely, except: don't remove our name from the source or
// documentation (don't take credit for my work), mark your changes (don't
// get me blamed for your possible bugs), don't alter or remove this
// notice.
// No warrantee of any kind, express or implied, is included with this
// software; use at your own risk, responsibility for damages (if any) to
// anyone resulting from the use of this software rests entirely with the
// user.
//
// Send bug reports, bug fixes, enhancements, requests, flames, etc. to
// softomatix@pardesiservices.com
///////////////////////////////////////////////////////////////////////////////
//

using System;
using System.Diagnostics;
using System.DirectoryServices;
using System.Xml;
using System.Collections;


namespace ASPNet_App
{
 /// <summary>
 ///
 /// </summary>
 public class ADSIUtil
 {
  protected string m_strErrors = "";
  protected string m_strRoot = "";
  protected DirectoryEntry m_obDirEntry;
  public ADSIUtil()
  {
   //
   // TODO: Add constructor logic here
   //
  }

  /// <summary>
  ///
  /// </summary>
  public string Errors
  {
   get
   {
    return m_strErrors;
   }
  }

  /// <summary>
  ///
  /// </summary>
  public string RootNode
  {
   get
   {
    return m_strRoot;
   }
   set
   {
    m_strRoot = value;
   }
  }

  /// <summary>
  ///
  /// </summary>
  /// <param name="strRoot"></param>
  /// <returns></returns>
  public bool Initialize(string strRoot)
  {
   if (m_strRoot == null || m_strRoot.Length == 0)
   {
    RootNode = strRoot;
   }

   try
   {
    m_obDirEntry = new DirectoryEntry(strRoot);
   }
   catch (Exception ex)
   {
    Trace.WriteLine(ex.Message);
    return false;
   }
   return true;
  }

  /// <summary>
  ///
  /// </summary>
  /// <returns></returns>
  public ArrayList GetUsersList()
  {
   ArrayList usersArr = new ArrayList();

   // Make sure that we have a root node specified.
   if (m_strRoot == null || m_strRoot.Length == 0)
   {
    m_strErrors += "Root Node not initializes";
    return usersArr;
   }

   SearchResultCollection results;
   DirectorySearcher srch = new DirectorySearcher(m_obDirEntry);
   srch.Filter = "(objectClass=User)";
   
   try
   {
    results = srch.FindAll();
   }
   catch (NotSupportedException ex)
   {
    m_strErrors += ex.Message;
    Trace.WriteLine(ex.Message);
    srch.Dispose();
    return usersArr;
   }
   catch (Exception ex)
   {
    m_strErrors += "\n";
    m_strErrors += ex.Message;
    Trace.WriteLine(ex.Message);
    srch.Dispose();
    return null;
   }
   try
   {
    foreach(SearchResult result in results)
    {
     ResultPropertyCollection propColl = result.Properties;
     ADSIUser user = new ADSIUser();
     if (false == user.Initialize(propColl))
     {
      m_strErrors += "\n";
      m_strErrors += "Failed to initialize the ADSI object";
      Trace.WriteLine("Failed to initialize the ADSI object");
      srch.Dispose();
      return null;
     }

     usersArr.Add(user);
    }
   }
   catch (Exception ex)
   {
    m_strErrors += "\n";
    m_strErrors += ex.Message;
    Trace.WriteLine(ex.Message);
    srch.Dispose();
    return null;
   }

   srch.Dispose();

   return usersArr;
  }
 }
}

// Disclaimer and Copyright Information
// ADSIUser.cs :
//
// All rights reserved.
//
// Written by Pardesi Services, LLC
// Version 1.0
//
// Distribute freely, except: don't remove our name from the source or
// documentation (don't take credit for my work), mark your changes (don't
// get me blamed for your possible bugs), don't alter or remove this
// notice.
// No warrantee of any kind, express or implied, is included with this
// software; use at your own risk, responsibility for damages (if any) to
// anyone resulting from the use of this software rests entirely with the
// user.
//
// Send bug reports, bug fixes, enhancements, requests, flames, etc. to
// softomatix@pardesiservices.com
///////////////////////////////////////////////////////////////////////////////
//

using System;
using System.Diagnostics;
using System.DirectoryServices;
using System.Xml;
using System.Text;

namespace ASPNet_App
{
 /// <summary>
 ///
 /// </summary>
 public class ADSIUser : ADSIObject
 {
  private string m_strLoginID = "";
  private string m_strFirstName = "";
  private string m_strLastName = "";
  private string m_strMiddleName = "";
  private string m_strDisplayName = "";
  //private string[] m_strMemberOf = null;
  private string m_strSID = "";
  private string m_strDateCreated = "";

  public ADSIUser()
  {
   //
   // TODO: Add constructor logic here
   //
  }

  /// <summary>
  ///
  /// </summary>
  public string LoginID
  {
   get
   {
    return this.m_strLoginID;
   }
  }

  /// <summary>
  ///
  /// </summary>
  public string DisplayName
  {
   get
   {
    return this.m_strDisplayName;
   }
  }

  /// <summary>
  ///
  /// </summary>
  public string FirstName
  {
   get
   {
    return this.m_strFirstName;
   }
  }

  /// <summary>
  ///
  /// </summary>
  public string LastName
  {
   get
   {
    return this.m_strLastName;
   }
  }

  /// <summary>
  ///
  /// </summary>
  public string MiddleName
  {
   get
   {
    return this.m_strMiddleName;
   }
  }

  /// <summary>
  ///
  /// </summary>
  public string UserSID
  {
   get
   {
    return this.m_strSID;
   }
  }

  /// <summary>
  ///
  /// </summary>
  public string CreationDate
  {
   get
   {
    return this.m_strDateCreated;
   }
  }

  /// <summary>
  ///
  /// </summary>
  protected override void ProcessUserData()
  {
   if (null == this.m_obPropertiesDoc)
   {
    return;
   }

   // Get login name..
   this.GetNodeValue("//adsi_object/name", ref this.m_strLoginID);

   // Get display name
   this.GetNodeValue("//adsi_object/displayname", ref this.m_strDisplayName);

   // Get first name
   this.GetNodeValue("//adsi_object/givenname", ref this.m_strFirstName);

   // Get Last name
   this.GetNodeValue("//adsi_object/sn", ref this.m_strLastName);

   // Get middle name
   this.GetNodeValue("//adsi_object/initials", ref this.m_strMiddleName);

   // Get creation date
   this.GetNodeValue("//adsi_object/whencreated", ref this.m_strDateCreated);
  }
 }
}


 

// Disclaimer and Copyright Information
// ADSIObject.cs :
//
// All rights reserved.
//
// Written by Pardesi Services, LLC
// Version 1.0
//
// Distribute freely, except: don't remove our name from the source or
// documentation (don't take credit for my work), mark your changes (don't
// get me blamed for your possible bugs), don't alter or remove this
// notice.
// No warrantee of any kind, express or implied, is included with this
// software; use at your own risk, responsibility for damages (if any) to
// anyone resulting from the use of this software rests entirely with the
// user.
//
// Send bug reports, bug fixes, enhancements, requests, flames, etc. to
// softomatix@pardesiservices.com
///////////////////////////////////////////////////////////////////////////////
//

using System;
using System.Diagnostics;
using System.Text;
using System.DirectoryServices;
using System.Xml;

namespace ASPNet_App
{
 /// <summary>
 ///
 /// </summary>
 public abstract class ADSIObject
 {
  protected bool m_bInitialized = false;
  protected int m_nNumProperties = -1;
  protected XmlDocument m_obPropertiesDoc = null;
  public ADSIObject()
  {
   //
   // TODO: Add constructor logic here
   //
  }

  /// <summary>
  ///
  /// </summary>
  /// <param name="propColl"></param>
  /// <returns></returns>
  public virtual bool Initialize(ResultPropertyCollection propColl)
  {
   // Check if the input collection object is null or not.
   if (null == propColl)
   {
    return false;
   }

   XmlNode obTopNode;
   try
   {
    // Create XMl Document to store values.
    m_obPropertiesDoc = new XmlDocument();
    obTopNode = this.AppendTopLevelNode();
    if (null == obTopNode)
    {
     Trace.WriteLine("Failed to add top level node to xml document");
     return false;
    }
    // Iterate over each key in the collection.
    foreach (string strKey in propColl.PropertyNames)
    {
     foreach (object obProp in propColl[strKey])
     {
      this.AppendPropertyNode(obTopNode, strKey, obProp);
     }
    }

    // Process the XML Document to store the information in local variables.
    this.ProcessUserData();

    this.m_nNumProperties = propColl.PropertyNames.Count;
    this.m_bInitialized = true;
   }
   catch (Exception ex)
   {
    Trace.WriteLine(ex.Message);
    return false;
   }
   return true;
  }

  /// <summary>
  ///
  /// </summary>
  /// <returns></returns>
  public XmlDocument GetProperties()
  {
   if (!m_bInitialized)
   {
    return null;
   }

   return m_obPropertiesDoc;
  }

  /// <summary>
  ///
  /// </summary>
  public int NumProperties
  {
   get
   {
    return m_nNumProperties;
   }
  }

  /// <summary>
  ///
  /// </summary>
  /// <returns></returns>
  protected virtual XmlNode AppendTopLevelNode()
  {
   XmlNode obTopNode = null;
   if (this.m_obPropertiesDoc == null)
   {
    return null;
   }

   StringBuilder strTopNode = new StringBuilder();
   strTopNode.Append ("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
   strTopNode.Append ("<adsi_object> </adsi_object>");

   try
   {
    m_obPropertiesDoc.LoadXml(strTopNode.ToString());
    obTopNode = m_obPropertiesDoc.SelectSingleNode("//adsi_object");
   }
   catch (Exception ex)
   {
    Trace.WriteLine(ex.Message);
    return null;
   }
   return obTopNode;
  }

  /// <summary>
  ///
  /// </summary>
  /// <param name="strNode"></param>
  /// <param name="prop"></param>
  /// <returns></returns>
  protected bool AppendPropertyNode(XmlNode node, string strNode, object prop)
  {
   try
   {
    XmlElement elem = this.m_obPropertiesDoc.CreateElement(strNode);
    XmlAttribute attrib = this.m_obPropertiesDoc.CreateAttribute("type");
    attrib.InnerText = prop.GetType().ToString();

    // Append the value type attribute to element.
    elem.Attributes.Append(attrib);

    // Append the value now...
    elem.InnerText = prop.ToString();

    // Append this element to top node.
    node.AppendChild(elem);
   }
   catch (Exception ex)
   {
    Trace.WriteLine(ex.Message);
   }
   return true;
  }

  /// <summary>
  ///
  /// </summary>
  protected virtual void ProcessUserData()
  {
  }

  /// <summary>
  ///
  /// </summary>
  /// <param name="strQuery"></param>
  /// <param name="strVal"></param>
  protected void GetNodeValue(string strQuery, ref string strVal)
  {
   try
   {
    XmlNode node = this.m_obPropertiesDoc.SelectSingleNode(strQuery);
    strVal = node.InnerText;
   }
   catch (Exception ex)
   {
    Trace.WriteLine(ex.Message);
   }
  }
 }
}

--------------------------------------------------------------------------

上面的这个类的使用方法如下:

---------------------------------------------------------------------------
 

/// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 private ArrayList GetUsersList()
 {
  ArrayList usersList = null;
  ADSIUtil obAdsi = new ADSIUtil();
  string strLDAP = "LDAP://pardesiservices.com";
  try
  {
   obAdsi.Initialize(strLDAP);
   usersList = obAdsi.GetUsersList();
   if (null == usersList)
   {
    Response.Write("<br>");
    Response.Write("** ");
    Response.Write(obAdsi.Errors);
    return null;
   }
  }
  catch (Exception ex)
  {
   Response.Write("<br>");
   Response.Write(ex.Message);

   Trace.Write(ex.Message);
   return null;
  }

  return usersList;
 }

------------------------------------------------------------------------

从上面的代码可以看出,
DirectorySearcher.FindAll() 方法得到的是SearchResultCollection,
SearchResultCollection得结构如下:


posted on 2005-11-11 17:13  今夜太冷  阅读(5526)  评论(0编辑  收藏  举报