Hi I'm trying to disable some users in my active directory with the following code below but I keep getting an "Object reference not set to an instance of an object" error message as shown in the attached image below.
I understand that this problem is because some of my users might be null.
What is the best way for me to go about resolving this?
DisableADUser method
//disable invalid accounts
    private static bool DisableADUser(string samAccountName)
    {
        bool result = false;
        try
        {    
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                    (principalContext, samAccountName);
            userPrincipal.Enabled = false;
            userPrincipal.Save();
            if (userPrincipal.Enabled == false)
            {
                Console.WriteLine("Account has been disabled successfully");
                result = true;
            }
            else
            {
                Console.WriteLine("\nUnable to disable account");
                result = false;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return result;
    }

Thanks in advance :)
EDITED CODE:
//disable invalid accounts
    private static bool DisableADUser(string samAccountName)
    {
        bool result = false;
        try
        {                
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                    (principalContext, samAccountName);
            if (userPrincipal != null)
            {
                userPrincipal.Enabled = false;
                userPrincipal.Save();
                if (userPrincipal.Enabled == false)
                {
                    Console.WriteLine("Account has been disabled successfully");
                    result = true;
                }
                else
                {
                    Console.WriteLine("\nUnable to disable account");
                    result = false;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return result;
    }
 
    