2012-02-16 16 views
0
DirectoryEntry testAD = new DirectoryEntry();  
DirectorySearcher search = new DirectorySearcher(testAD); 

StringBuilder add = new StringBuilder(); 
search.PropertiesToLoad.Add("mail"); 
search.Filter = "(&(objectClass=user))"; 

foreach (SearchResult SearchAll in search.FindAll()) 
{ 
    DirectoryEntry de = SearchAll.GetDirectoryEntry(); 
    add.Append(de.Properties["mail"].Value.ToString()); // error message here 
} 

PrefixDescription.Text = add.ToString(); 

我試圖首先查找所有電子郵件作爲測試,然後將所有信息(名字,姓氏等)和使用LPAR過濾器的文本框中列出,但我不斷收到此錯誤當我運行應用程序時出現以下消息:使用LDAP過濾器查找所有結果。獲取錯誤信息

未將對象引用設置爲對象的實例。

回答

2

那麼,你正在枚舉用戶 - 但你不能保證得到的用戶將有一個電子郵件地址!你需要基本的「編程101」錯誤預防:

..... 
foreach (SearchResult result in search.FindAll()) 
{ 
    // this is totally unnecessary - the "SearchResult" already *contains* all 
    // the properties you've defined in your "PropertiesToLoad" collection! 
    // DirectoryEntry de = SearchAll.GetDirectoryEntry(); 

    if(result.Properties["mail"] != null && result.Properties["mail"].Count > 0) 
    { 
     add.Append(result.Properties["mail"][0].ToString()); 
    } 
} 

有了這個額外的檢查,您避免Object reference not set....錯誤...

+0

哈哈,謝謝,我很懶惰,因爲對方根本不關心錯誤預防當我用其他方法玩耍時,它只輸出一個空白區域。當我沒有正確實例化瞬間時,我通常會看到該錯誤消息,所以我從來不知道錯誤與此相關!謝謝marc。 – nhat 2012-02-16 18:36:29

相關問題