index out of range RRS feed

  • Question

  • please see below at the if statement I get error when mail attribute is empty// public class Users { public string mail { get; set; } public string UserName { get; set; } public string DisplayName { get; set; } } static void Main(string[] args) { List<Users> lstADUsers = new List<Users>(); string DomainPath = "LDAP://DC=teksite,DC=local"; DirectoryEntry searchRoot = new DirectoryEntry(DomainPath); DirectorySearcher search = new DirectorySearcher(searchRoot); search.Filter = "(&(objectClass=user)(objectCategory=person))"; search.PropertiesToLoad.Add("samaccountname"); search.PropertiesToLoad.Add("mail"); search.PropertiesToLoad.Add("displayname");//first name SearchResult result; SearchResultCollection resultCol = search.FindAll(); if (resultCol != null) { for (int counter = 0; counter < resultCol.Count; counter++) { string UserNameEmailString = string.Empty; result = resultCol[counter]; if (result.Properties.Contains("samaccountname") && result.Properties.Contains("displayname")) { Users objSurveyUsers = new Users(); objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0]; objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0]; if (String.IsNullOrEmpty((String)result.Properties["mail"][0])) // here I am getting Error Index out of range { // do nothing } else { string y = (String)result.Properties["mail"][0];

    objSurveyUsers.mail = (String)result.Properties["mail"][0]; } lstADUsers.Add(objSurveyUsers); } } Console.Write(lstADUsers); } Console.ReadLine(); }

    • Edited by asif300 Wednesday, September 4, 2019 11:25 PM
    Wednesday, September 4, 2019 11:02 PM


  • Do this before attempting to access the data.

    Put a breakpoint on Console.WriteLine

    var mailData = result.Properties["mail"];

    Examone mailData, my guess it's null for elements.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    • Marked as answer by asif300 Thursday, September 5, 2019 12:12 AM
    Wednesday, September 4, 2019 11:09 PM