我是使用C#的新手,这是我第二次将它与活动目录结合使用。我不断收到错误:对象引用未设置为对象的实例。以下是我的代码。我知道我的空引用是在var result = searcher.FindOne();
行我不确定我需要做什么来解决这个问题。C#搜索Active Directory错误
static void Main(string[] args)
{
List<string> userList = new List<string>();
try
{
string[] newUsers = { List of users is here ex: [email protected], [email protected], ... };
PrincipalContext AD = new PrincipalContext(ContextType.Domain, "xyz.com");
UserPrincipal u = new UserPrincipal(AD);
PrincipalSearcher search = new PrincipalSearcher(u);
DirectorySearcher searcher = new DirectorySearcher();
foreach (string x in newUsers)
{
searcher.Filter = string.Format("(&(objectCategory=person)(anr={0}))", x);
var result = searcher.FindOne();
userList.Add(string.Format("{0} {1}", result.Properties["DisplayName"][0].ToString(), result.Properties["Company"][0].ToString()));
search.Dispose();
}
foreach(string y in userList)
{
Console.WriteLine(y);
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
File.WriteAllLines(file location, userList);
}
可能重复[什么是一个NullReferenceException,如何解决呢?(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i -fix-it) –
你是否尝试过调试?这是找出发生异常的代码行的非常确定的方法。 – Jim
您不检查search.FindOne()返回null,如果您的数组中的某个用户名被错误地指定,它可能会执行此操作。 –