禁用AD用户错误:未将对象引用设置为对象的实例

时间:2015-04-07 01:43:57

标签: c# visual-studio-2010 active-directory object-reference

您好我正在尝试使用以下代码禁用我的活动目录中的某些用户,但我不断收到“对象引用未设置为对象的实例”错误消息,如附件图如下。

我知道这个问题是因为我的一些用户可能是null。

我最好的解决方法是什么?

DisableADUser方法

//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;
    }

Object reference not set to an instance of an object Error

提前致谢:)

编辑代码:

//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;
    }

0 个答案:

没有答案