2016-09-12 1 views
-2

私たちの会社のドメイン内のすべてのユーザーの電子メールアドレスを取得しようとしています。 99%は動作しますが、出力にy NullReferenceExceptionがあることがあります。C#Active Directory - 電子メールNullReferencesExceptionを読み取る

コード:

string dom = "mydomain"; 

System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + dom); //domain, user, password 
System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(entry); 

ds.Filter = ("(objectClass=User)"); 
int count = 1; 

foreach (System.DirectoryServices.SearchResult resEnt in ds.FindAll()) 
{ 
    try 
    { 
     System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry(); 
     String email = de.Properties["mail"].Value.ToString(); 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e.ToString()); 
    } 
} 
+1

が、私は実際にあなたのポストに質問が表示されません。あなたの質問は何ですか? – mason

+0

誰かが、いつも 'code'Stringの行にnull参照例外があるのを知っているなら、email = de.Properties [" mail "] Value.ToString();' code' – Flowe

+0

//編集:私は377の電子メールアドレスドメインには383があります...もし私が私のアプリケーションのログに6個のnullpointersがあるなら誰でもこのコードがこの6人のユーザのためには動かないことを知っていますか? – Flowe

答えて

0

null値またはそのValueプロパティがnullあるProperties["mail"]リターンの場合、その試みはToString()意志を呼び出すために、ライン

String email = de.Properties["mail"].Value.ToString(); 

NullReferenceExceptionがあるかもしれません例外が発生します。これは、この場合に役立ちます

(C#6構文)

String email = de.Properties["mail"]?.Value?.ToString(); 

または

String email = null; 
if (de.Properties["mail"] != null && de.Properties["mail"].Value != null) 
{ 
    email = de.Properties["mail"].Value.ToString(); 
} 
+0

それは私に多くを助けてくれてありがとう – Flowe

+0

@フローウ - あなたは歓迎です。あなたの問題を解決した場合は、投稿を「回答」としてください。 –

関連する問題