2017-03-29 100 views
1

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

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

请在您的问题更加清晰和添加代码时,是描述性的。 – ThatAwesomeCoder

+0

是的,我的错误。我已经添加了几个描述。 我想禁用活动目录用户使用C#但无法计算如何链接文本框条目与此代码。 –

+0

你指的是“文本框条目”? C#表单应用程序TextBox? – ThatAwesomeCoder

回答

1

试试下面的例子:

C#代码

首先添加事件点击您的按钮:

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

然后在同一类定义你的方法由于保护级别是私人的 否则如果它是德在另一类/装配裁判判罚再进行保护层次的公共

// 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"; 
    } 
} 
+0

好吧,我确实做到了,进入了文本框的用户名,但得到以下错误。 '在WindowsFormsApplication2.exe中发生了类型'System.NullReferenceException'的第一次机会异常 未设置对象实例的对象引用。' –

+0

将您的类的按钮单击事件和代码添加到您的问题中,以便我可以分析它。 – ThatAwesomeCoder

+0

确定这是完整的代码 https://pastebin.com/G4vqEZg7 –

相关问题