使用C#代码禁用Active Directory中的用户帐户

时间:2017-03-29 05:06:50

标签: c#

我创建了c#Winform应用程序。通过它我可以使用C#代码禁用活动目录用户帐户。我添加了一个文本框,我可以在其中输入我的AD用户名。但无法确定如何将此文本框条目与下面的代码链接?

private static void DiableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain); 
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                (principalContext, username);
        userPrincipal.Enabled = false;
        userPrincipal.Save();
        Console.WriteLine("Active Directory User Account Disabled successfully through UserPrincipal");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

1 个答案:

答案 0 :(得分:3)

尝试以下示例:

C#CODE

首先添加一个事件点击你的按钮:

// Button click event
private void btnDisableAcc_Click(object sender, EventArgs e)
{
    // When the user clicks the button
    String _ADUserName = textBox1.Text; // <-- The textbox you enter your username?

    // Call the method below 'DiableADUserUsingUserPrincipal'
    DiableADUserUsingUserPrincipal(_ADUserName); // <-- Pass in the user name via the local variable
}

然后在同一类中定义您的方法,因为保护级别是私有的 否则,如果它在另一个类/程序集ref中定义,则将保护级别公开

// Private Method
private static void DiableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                (principalContext, username);
        userPrincipal.Enabled = false;
        userPrincipal.Save();

        MessageBox.Show("AD Account disabled for {0}", username);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

启用帐户:

// Private Method with return type "Boolean" to determine if the method succeed or not.
private static bool EnableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
        (principalContext, username);
        userPrincipal.Enabled = true;
        userPrincipal.Save();

        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return false;
}


private void button2_Click(object sender, EventArgs e)
{
    String _ADUserName = textBox1.Text; // <-- The textbox you enter your username?

    // Check if the account is enabled
    if (EnableADUserUsingUserPrincipal(_ADUserName))
    {
        MessageBox.Show("AD Account Enabled for {0}", _ADUserName );
        this.StatusTextBox.Text = "Account Enabled";
    }
}