1

I am pretty new to using C# and this is my second time using it with active directory. I keep getting the error: Object reference not set to an instance of an object. Below is my code. I know that my null reference is in the line var result = searcher.FindOne(); I am unsure of what I need to do to fix this.

static void Main(string[] args)
    {
        List<string> userList = new List<string>();

        try
        {


            string[] newUsers = { List of users is here ex: jsmith@xyz.com, bsmith@xyz.com, ... };

            PrincipalContext AD = new PrincipalContext(ContextType.Domain, "xyz.com");
            UserPrincipal u = new UserPrincipal(AD);
            PrincipalSearcher search = new PrincipalSearcher(u);
            DirectorySearcher searcher = new DirectorySearcher();

            foreach (string x in newUsers)
            {
                searcher.Filter = string.Format("(&(objectCategory=person)(anr={0}))", x);

                var result = searcher.FindOne();

                userList.Add(string.Format("{0} {1}", result.Properties["DisplayName"][0].ToString(), result.Properties["Company"][0].ToString()));

                search.Dispose();
            }

            foreach(string y in userList)
            {
                Console.WriteLine(y);
            }

            Console.ReadLine();
        }

        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }

        File.WriteAllLines(file location, userList);
    }
ghd0002
  • 25
  • 4
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Salah Akbari Aug 21 '15 at 18:21
  • Have you tried debugging at all? That's a pretty surefire way to find out which line of code the exception is occurring on. – Jim Aug 21 '15 at 18:23
  • 1
    You are not checking for search.FindOne() returning null, which it may do if one of those user names in your array is incorrectly specified. – Jeff Prince Aug 21 '15 at 18:24
  • I know that it is my var result = searcher.FindOne(); that is null I am just not sure how to fix this issue. – ghd0002 Aug 21 '15 at 18:26

2 Answers2

0

As several commenters have noted, your code is not handling the situation where no user is found by DirectorySearcher.FindOne - and, as noted in the MSDN documentation, FindOne returns null if no user is found:

If more than one entry is found during the search, only the first entry is returned. If no entries are found to match the search criteria, a null reference (Nothing in Visual Basic) is returned.

So you'll need to handle the case where the user you're looking for isn't there:

    foreach (string x in newUsers)
    {
        Console.WriteLine("looking for user {0}", x);
        searcher.Filter = string.Format("(&(objectCategory=person)(anr={0}))", x);
        var result = searcher.FindOne();
        if (result == null)
        {
            userList.Add(String.Format("user {0} not found!", x));
        }
        else 
        {
            userList.Add(string.Format("{0} {1}", result.Properties["DisplayName"][0].ToString(), result.Properties["Company"][0].ToString()));
        }
        search.Dispose();
    }
Edmund Schweppe
  • 4,992
  • 1
  • 20
  • 26
0

Your problem is that you're declaring PrincipalSearcher and DirectorySearcher, yet you're only populating the PrincipalSearcher with UserPrincipal object.

...
UserPrincipal u = new UserPrincipal(AD);
PrincipalSearcher search = new PrincipalSearcher(u);
...

However, your DirectorySearcher object searcher is empty.

DirectorySearcher searcher = new DirectorySearcher();

In foreach loop you're searching for one user using DirectorySearcher object not PrincipalSearcher:

var result = searcher.FindOne();

The above line will always return null. You need to populate DirectorySearcher.

DirectorySearcher searcher = new DirectorySearcher(/*need a DirectoryEntry*/);

I would suggest you take full advantage of UserPrincipal class. It seems that you want to search for users in Active Directory and you know their UserPrincipal names.

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
    string [] newUsers; //need to declare list of new users
    foreach (string user in newUsers)
    {
       using (UserPrincipal newUser = UserPrincipal.FindByIdentity(ctx, IdentityType.UserPrincipalName, user))
       {
          if (newUser != null)
          {
            //do what you need to do
            //newUser will contain all info on a particular user
          }
       }
   }
}
smr5
  • 2,593
  • 6
  • 39
  • 66