以下是我的代码:
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 有关 - 但我可能是错的。:-)