Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我会得到;对象引用未设置为对象的实例;在这里_C#_.net_Directorysearcher - Fatal编程技术网

C# 为什么我会得到;对象引用未设置为对象的实例;在这里

C# 为什么我会得到;对象引用未设置为对象的实例;在这里,c#,.net,directorysearcher,C#,.net,Directorysearcher,以下是我的代码: DirectorySearcher search = new DirectorySearcher( directory ); search.Filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(|(sn=*)))"; search.PropertiesToLoad.Add( "GivenName" ); search.Pr

以下是我的代码:

DirectorySearcher search = new DirectorySearcher( directory );

search.Filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(|(sn=*)))";
search.PropertiesToLoad.Add( "GivenName" );
search.PropertiesToLoad.Add( "OfficePhone" );
search.PropertiesToLoad.Add( "EmployeeNumber" );


SearchResultCollection results = search.FindAll();

int thisCount = results.Count;
string filePath = "C:\\test.csv";

string contents = string.Empty;
int counter = 0;
foreach( SearchResult result in results ) {
  DirectoryEntry userEntry = result.GetDirectoryEntry();

  string givenName = userEntry.Properties[ "userPrincipalName" ].Value.ToString();
  string employeeNumber = userEntry.Properties[ "EmployeeNumber" ].Value.ToString();
  string phoneNumber = userEntry.Properties[ "OfficePhone" ].Value.ToString();

  counter = counter + 1;
}
System.IO.File.WriteAllText( filePath, contents );
我似乎无法回避的问题是,当我开始循环“results”对象时,在分配了
givenName
之后,代码就会爆炸。
我得到的错误是:

对象引用未设置为对象的实例


我试图找出如何正确地分配这个,但我总是遇到麻烦。如有任何建议,将不胜感激。我很确定这与我没有正确理解DirectorySearcher/DirectoryEntry有关,但我可能错了。:-)

根据这一说法:

在givenName被分配后,代码爆炸了

这行代码:

userEntry.Properties[ "EmployeeNumber" ]
正在爆炸并让您知道没有名为
EmployeeNumber
的属性,或者
EmployeeNumber
null
。我要赌第二个,所以把这一行改为:

userEntry.Properties[ "EmployeeNumber" ] as string;
null
时,您的
employeeNumber
字段将设置为
null
,但不会引发异常

userEntry.Properties[ "EmployeeNumber" ].Value as string; 

“已工作”

听起来您有一个空属性…如果此目录项上没有设置
EmployeeNumber
,则
userEntry.Properties[“EmployeeNumber”]
将为
null
,对其调用
.Value.ToString()
将导致此异常。您必须在此处检查
NULL
!谢谢,但不要雪茄。我试了你们的建议,但还是有同样的错误。我想知道这是否与GivenName是一个库存字段,而OfficePhone和EmployeeNumber是自定义字段有关?@user1250636,如果您仍然得到一个
NullReferenceException
,那么我的第一个假设比上一个假设更正确:
爆炸了,让您知道没有名为EmployeeNumber的属性…
。现在,你是说这些实际上是在所有对象上定义的?嘿,伙计们-我的错:“userEntry.Properties[“EmployeeNumber”]。Value as string;”起作用了。谢谢