第488篇-Find specified user in AD--(8)

 If you are developing a project related to AD(Active Directory), you probably need to search a particular user by its user name, surely you can create a method to achieve you own algorithm, but if the system provide a build-in one, I suggest you can just take the advantage the build-in method, which is quite optimized. In this post, I would like to share with you how to find a specified user using two corresponding methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.Collections;
using System.DirectoryServices.ActiveDirectory;
namespace ConsoleApplicationTest
{
    class Program
    {
        static void Main(string[] args)
        {

        }

        /// <summary>
        /// Search the user by using filter  (ok )
        /// </summary>
        /// <param name="de"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public string SearchUser(string username)
        {
         
            //string[] msg;
            string ldapPath = string.Empty;
            string _path = Domain.GetCurrentDomain().GetDirectoryEntry().Path;
            DirectoryEntry entry = new DirectoryEntry(_path);

            //Bind to the native AdsObject to force authentication.
            Object obj = entry.NativeObject;
            System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
            mySearcher.Filter = "(SAMAccountName=" + username + ")";
            msg = new string[mySearcher.FindAll().Count];
            int i = 0;
            foreach (System.DirectoryServices.SearchResult result in mySearcher.FindAll())
            {
                //msg[i++] = result.Path;
            }
            return msg;
        }
/// <summary> /// By members /// </summary> /// <param name="dirEntry"></param> /// <param name="filter"></param> public void SearchUser2(DirectoryEntry dirEntry, string filter) { object members = dirEntry.Invoke("Members", null); //传入dev.spdb.com foreach (object member in (IEnumerable)members) { System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry(member); String distName = GetStringProperty(de.Properties, "distinguishedName"); String prefix = (string)de.Properties["objectCategory"][0]; int startPos = 0; int endPos = 0; startPos = prefix.IndexOf("=") + 1; endPos = prefix.IndexOf(",", startPos); prefix = prefix.Substring(startPos, endPos - startPos); } } private string GetStringProperty(PropertyCollection properties,string propertyName) { string value=string.Empty; foreach (string name in properties.PropertyNames) { value=properties[propertyName][0].ToString(); } return value ; } } public class User { } }

 

posted @ 2013-01-20 17:22  Shanghai Jim Zhou  阅读(352)  评论(0编辑  收藏  举报