刚才处理了一个这样的问题,代码摘录如下
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();
}
}
}
如果该用户没有填写公司信息,则会报错。