user3200722
user3200722

Reputation: 7

Unhandled Exception Active Directory

I am new to active directory and i am trying to display details from the group category in Active Directory. Here is my code for the following:

entry = new DirectoryEntry(strPath);

DirectoryEntry schema = entry.SchemaEntry;
System.DirectoryServices.DirectorySearcher myNewSearcher = new System.DirectoryServices.DirectorySearcher(entry);

mySearcher.Filter = ("(objectClass=*)");

foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
{
    Console.WriteLine("First Name: " + resEnt.Properties["givenName"][0].ToString());
    Console.WriteLine("Last Name : " + resEnt.Properties["sn"][0].ToString());
    Console.WriteLine("SAM account name   : " + resEnt.Properties["samAccountName"][0].ToString());
    Console.WriteLine("User principal name: " + resEnt.Properties["userPrincipalName"][0].ToString());
    Console.WriteLine();
}

The error that I am getting is:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

Can I get some help?

Upvotes: 0

Views: 474

Answers (1)

marc_s
marc_s

Reputation: 755237

AD properties might not be set - and in this case, you call to .Properties[..][0] will cause this exception.

You need to check for every property returned from the DirectorySearcher whether it's set - or not:

if(resEnt.Properties["givenName"] != null && resEnt.Properties["givenName"].Count > 0) {
   Console.WriteLine("First Name: " + resEnt.Properties["givenName"][0].ToString());
}

Upvotes: 3

Related Questions