Reputation: 246
I have created c# Winform application. via which I can disable an active directory user account using C# code. I have added a textbox in which I can enter my AD username. But unable to figure how to link this textbox entry with below code?
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);
}
}
Upvotes: 2
Views: 7942
Reputation: 1583
Try the following example:
C# CODE
First add an event click to your button:
// 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
}
Then define your method in the same class due to protection level is private otherwise if it is defined in another class / assembly ref then make the protection level public
// 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);
}
}
To enable the account:
// 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";
}
}
Upvotes: 4