# Saturday, 27 March 2010
« File parsing with open source FileHelper... | Main | First day of the week in .Net »

I need to take a CSV file of logins with their emails and verify if these logins exist in our Active Directory.  This can be done several different ways including with powershell but for one reason or another I want/need to do it with .Net.

I will be using an open source library called FileHelpers to make the parsing of the CSV file a snap.  I’m going to skip over the code that uses FileHelpers and focus on the AD lookup.  Check out my previous post on FileHelpers to see how easy FileHelpers makes parsing.

I’m going to use the System.DirectoryServices namespace to lookup AD information.

Let’s look at the AD Lookup class I created to compare the login in the CSV file to AD.

using System;
using System.Collections.Generic;
using System.DirectoryServices;

namespace VerifyUsers
{
    public class ADLookup
    {
        private DirectorySearcher _directoryToSearch;

        public ADLookup()
        {
            DirectoryEntry root = new DirectoryEntry("LDAP://rootDSE");
            string rootName = "LDAP://" + root.Properties["defaultNamingContext"].Value.ToString();
            DirectoryEntry searchRoot = new DirectoryEntry(rootName);
            _directoryToSearch = new DirectorySearcher(searchRoot);
            _directoryToSearch.PageSize = 100;
            _directoryToSearch.SearchScope = SearchScope.Subtree;
            _directoryToSearch.PropertiesToLoad.Add("displayName");
        }

        public bool IsUserInAD(string login)
        {
            _directoryToSearch.Filter = string.Format("(&(sAMAccountName={0})(objectClass=Person))", login);
            SearchResultCollection personFound = _directoryToSearch.FindAll();

            return personFound.Count > 0;
        }
    }
}

I’m using the DirectorySearcher class to look in AD for user information.  In the class constructor I setup the connection information to the LDAP store and set some of the basic properties.

The SearchScope property is important to set to what you need.  I set it to Subtree (which is the default) to have search include the base and it’s children.  If for example, your AD environment has subfolders then you want this set in order to search the subfolders.

In the IsUserInAD method call I setup the query to look for the login name better known as the sAMAccountName in LDAP and I only want it to search Person objects.

Note – If you are creating your own project you will need to add a reference to System.DirectoryServices.

Now let’s get the code running in a console:

using System;
using System.Collections.Generic;

namespace VerifyUsers
{
    class Program
    {
        static void Main(string[] args)
        {
            Parser userParser = new Parser("Users.csv");
            DisplayUsersNotInAD(userParser.Parse());

            Console.ReadLine();
        }

        static void DisplayUsersNotInAD(User[] list)
        {
            ADLookup lookup = new ADLookup();
            foreach (User u in list)
                if (lookup.IsUserInAD(u.login) == false)
                    Console.WriteLine("{0} was not found in AD.", u.login);
        }
    }
}

First, we parse the CSV file using the FileHelpers library.  Then we iterate over the list and display the entries not found in our directory.

The CSV file I am using has three entries and the first two are bogus accounts that don’t exist in AD.  The third entry does.  If the code works correctly we should only have the first two entries reported as not found.

When you run the code you should see:

image

The last entry, kdog, was found in AD.  We can do whatever we need to with the two entries that aren’t in AD.

Download the C# source or VB Source.

Read my previous post on using the open source FileHelpers library to parse CSV files.

Happy Coding!

Posted 03.27.2010  #    Comments [0]  |