1

以下是我的代码:

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 );

我似乎无法解决的问题是,当我开始循环遍历“结果”对象时,代码在分配后会爆炸。givenName 我得到的错误是:

你调用的对象是空的。

我试图弄清楚如何正确分配它,但我一直遇到它。任何建议将不胜感激。我很确定这与我没有正确理解 DirectorySearcher/DirectoryEntry 有关 - 但我可能是错的。:-)

4

2 回答 2

1

基于此声明:

分配给定名称后代码会爆炸......

这行代码:

userEntry.Properties[ "EmployeeNumber" ]

正在爆炸并让您知道没有名为的属性EmployeeNumber ValueofEmployeeNumbernull。我打算赌第二个,所以把那一行改成这样:

userEntry.Properties[ "EmployeeNumber" ] as string;

并且您的employeeNumber字段将设置为何null时,null但不会引发异常。

于 2013-06-06T20:02:53.150 回答
1
userEntry.Properties[ "EmployeeNumber" ].Value as string; 

工作过

于 2013-06-07T15:43:14.267 回答