2016-09-12 3 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에 nullreference 예외가있는 이유를 아는 사람이있는 경우 email = de.Properties [ "mail"] .Value.ToString();'code' – Flowe

+0

// 편집 : 나는 377 개의 이메일 주소를 얻습니다. 도메인 거기에 383 ... 만약 내가 내 응용 프로그램의 로그에 보면 6 nullpointers ..이 코드는이 6 사용자의 작동하지 않습니다 누구 아시나요? – Flowe

답변

0

라인에 NullReferenceException가있을 수 있습니다

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

Properties["mail"]null 값 반환 또는 Value 속성, ToString()를 호출 한 후 시도 null이다에서 만약 것 예외가 생깁니다. 이이 경우에 도움이 될 것입니다

(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

@Flow - 오신 것을 환영합니다. 게시물이 문제를 해결 한 경우 해당 게시물을 "답변"으로 표시하십시오. –