您好我正在尝试使用以下代码禁用我的活动目录中的某些用户,但我不断收到“对象引用未设置为对象的实例”错误消息,如附件图如下。
我知道这个问题是因为我的一些用户可能是null。
我最好的解决方法是什么?
//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;
}
提前致谢:)
编辑代码:
//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;
}