Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1477
  • Last Modified:

c# active directory DirectoryEntry error if blank, Index was out of range.

hi all, im getting an error when an active directory attriuble is blank in my c# app

for the user im testing it on, Tel and Fax are blank (it stops at tel though with fatal exception)

System.TypeInitializationException: The type initializer for 'GlobalFunc' threw an exception. ---> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

looking at my code below anyone tel me why and how i can ignore if its blank?

DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + _Domain, null, null, AuthenticationTypes.Secure);
                DirectorySearcher searcher = new DirectorySearcher(adRoot);
                searcher.SearchScope = SearchScope.Subtree;
                searcher.ReferralChasing = ReferralChasingOption.All;
                searcher.Filter = filter;

                SearchResult result = searcher.FindOne();
                DirectoryEntry directoryEntry = result.GetDirectoryEntry();

                //string displayName = directoryEntry.Properties["displayName"][0].ToString();
                FirstName = directoryEntry.Properties["givenName"][0].ToString();
                Surname = directoryEntry.Properties["sn"][0].ToString();
                EmailAddress = directoryEntry.Properties["mail"][0].ToString();
                Company = directoryEntry.Properties["company"][0].ToString();
                Tel = directoryEntry.Properties["telephoneNumber"][0].ToString();
                Fax = directoryEntry.Properties["facsimileTelephoneNumber"][0].ToString();
                JobTitle = directoryEntry.Properties["title"][0].ToString();
                lockoutStatus = directoryEntry.InvokeGet("IsAccountLocked").ToString();

Open in new window

  • 3
1 Solution
Daniel Van Der WerkenIndependent ConsultantCommented:
Can you test for null?

if ( directoryEntry.Properties["company"][0]  != null )
   Tel = directoryEntry.Properties["company"][0].ToString();
awilderbeastAuthor Commented:
i dont think the problem is testing for null, because im not actually assigning tel to anything the problem is if the attribute in AD is null

what about a try catch? that might work eh?
awilderbeastAuthor Commented:
try catch sorted it! :)
awilderbeastAuthor Commented:
figured it out

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now