gestalt
gestalt

Reputation: 375

Query Active Directory in C#

I am trying to perform a query to Active Directory to obtain all the first names of every user. So I have created a new console application and in my main method have the following code:

try  
{   
    DirectoryEntry myLdapConnection =new DirectoryEntry("virtual.local");
    myLdapConnection.Path = "LDAP://DC=virtual,DC=local";   

    DirectorySearcher search = new DirectorySearcher(myLdapConnection);  
    search.PropertiesToLoad.Add("cn");   

    SearchResultCollection allUsers = search.FindAll();

I have added some code to check that the connection is being made and that the path can be found. I also ensure that the Collection is not empty.

    //For Debugging
    if(DirectoryEntry.Exists(myLdapConnection.Path())
    {
        Console.WriteLine("Found");
    }
    else Console.WriteLine("Could Not Find LDAP Connection");

    //In my case prints 230
    Console.WriteLine("Total Count: " + allUsers.Count);

    foreach(SearchResult result in allUsers)  
    {  
        //This prints out 0 then 1
        Console.WriteLine("Count: " + result.Properties["cn'].Count);

        if (result.Properties["cn"].Count > 0)  //Skips the first value
        {  
            Console.WriteLine(String.Format("{0,-20} : {1}",  
                result.Properties["cn"][0].ToString()));  //Always fails
        }  
     }    
}  
catch (Exception e)  
{  
    Console.WriteLine("Exception caught:\n\n" + e.ToString());  
}    

I have specified in the code, where it prints out the properties, that it always fails. I get a System.FormatException being caught here that states the Index must be greater than zero and less than the size of the argument list.

So in the end I'm not really sure how "result.Properties" works and was wondering if you had any advise on how to fix or troubleshoot the problem.

Upvotes: 0

Views: 217

Answers (1)

Chris Ballard
Chris Ballard

Reputation: 3769

You are defining two format specifiers {0} and {1} but only specifying one argument.

Upvotes: 1

Related Questions