读取AD信息的例子

刚才处理了一个这样的问题,代码摘录如下

using System;
using System.Collections.Generic;
using System.Text;

using System.DirectoryServices; //需要添加这个程序集引用先

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetCompanyFromAD(@"chenxizhang"));
            Console.Read();
        }

        public static String GetCompanyFromAD(String username)
        {
            DirectoryEntry de = new DirectoryEntry("LDAP://server2003", @"xizhang\administrator", "password");
            DirectorySearcher ds = new DirectorySearcher(de);
            ds.Filter = "(&(objectClass=user)( sAMAccountName=" + username + "))";
            SearchResult sr = ds.FindOne();
            DirectoryEntry resultDE = sr.GetDirectoryEntry();
            return (" " + resultDE.Properties["company"].Value.ToString() + " ").Trim();
        }

    }
}

如果该用户没有填写公司信息,则会报错。

posted @ 2009-06-03 22:21  陈希章  阅读(761)  评论(0编辑  收藏  举报