c#winform活动目录:如果登录成功,则访问另一个表单

我想从一个表单创建一个控件,我有登录文本框和密码文本框,以及登录按钮。 当我要输入活动目录帐户名称及其密码时,我想转到另一个表单。 有人可以帮我这个。 在此代码示例中,我选择仅用于登录的帐户。 我想选择它并键入密码并通过例如从表单(登录)到表单(用户界面)的目标表单。

private void radiobtnAD_CheckedChanged(object sender, EventArgs e) { if (radiobtnAD.Checked) { try { string filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))"; string[] propertiesToLoad = new string[1] { "name" }; using (DirectoryEntry root = new DirectoryEntry("LDAP://DOMAIN")) using (DirectorySearcher searcher = new DirectorySearcher(root, filter, propertiesToLoad)) using (SearchResultCollection results = searcher.FindAll()) { foreach (SearchResult result in results) { string name = (string)result.Properties["name"][0]; comboBox1.Items.Add(name); } } } catch { } } } 

这是您的代码,已编辑。

  1. validation文本框(!string.Empty)。
  2. validation凭据。
  3. 根据用户类型显示所需的表单。

当你正确地分割你的代码时,这很容易。

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using LibXmlSettings.Settings; using Microsoft.ApplicationBlocks.Data; using System.Data.Sql; using System.Data.SqlClient; using System.Data.SqlTypes; using System.DirectoryServices; using System.IO; using System.Linq.Expressions; using System.Runtime.InteropServices; using System.DirectoryServices.AccountManagement; namespace GestionnaireDesPlugins { public partial class Login : Form { public Login(string accountName, string accountPassword) { InitializeComponent(); } private void LoginOnClick(object sender, EventArgs e) { if (IsValid()) { GetUser(); // Do whatever you want ShowForm(); } } private void GetUser() { try { LdapConnection connection = new LdapConnection("AD"); NetworkCredential credential = new NetworkCredential(txtboxlogin.Text, txtboxpass.Text); connection.Credential = credential; connection.Bind(); } catch (LdapException lexc) { String error = lexc.ServerErrorMessage; MessageBox.Show("error account or password."); } catch (Exception exc) { MessageBox.Show(exc.ToString()); } } private bool IsValid() { // Check if the user haven't chosen an account if (!string.IsNullOrEmpty(txtboxlogin.Text) { return false; } // Check if the user haven't chosen an account if (!string.IsNullOrEmpty(txtboxpass.Text)) { return false; } // Check if the user haven't chosen an account if (!string.IsNullOrEmpty(comboBox1.Text)) { return false; } // Check if the password TextBox is empty if (!string.IsNullOrEmpty(textBox1.Text)) { return false; } using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN")) { // validate the credentials bool isValid = pc.ValidateCredentials(txtboxlogin.Text, txtboxpass.Text); } return isValid; } private void ShowForm() { if (txtboxlogin.Text == "WantedAdminUser") { using (AdminForm form2 = new AdminForm()) form2.ShowDialog(); Show(); } else { using (user userform = new user()) userform.ShowDialog(); Show(); } } } } 

如前所述,由于您是C#的新手,这里有一些建议:

  1. 拆分代码:方法必须简短并按目的分开。 对于您和任何处理代码的人来说,这样更容易
  2. 管理例外
  3. 处理对象
  4. 注意这个txtboxlogin.Text == "WantedAdminUser"这很危险。

因此,您有一个表单,其中ComboBox中填充了帐户名称,一个用于输入密码的TextBox,以及一个用于打开新表单的Button。

将TextBox的属性PasswordChar为所需的掩码字符:

 textBox1.PasswordChar = '*'; 

通过在设计器中双击登录按钮,为其创建一个新的单击方法。 它应该创建一个新的处理程序:

 private void loginButton_Click(object sender, EventArgs e) { // Check if the user haven't chosen an account if (comboBox1.Text == "") { return; } // Check if the password TextBox is empty if (textBox1.Text == "") { return; } // Create a new method for checking the account and password, which returns a bool bool loginSuccess = CheckUserInput(comboBox1.Text.Trim(), textBox1.Text); if (loginSuccess) { // Create a new instance of your user-interface form. Give the account name and password // to it's constructor UserForm newForm = new UserForm(comboBox1.Text.Trim(), textBox1.Text.Trim())) // Show the created UserForm form newForm.Show(); // Close this login form this.Close(); } } 

编辑UserForm表单构造函数以获取2个字符串参数:

 public UserForm(string accountName, string accountPassword) { InitializeComponent(); // ... } 

添加2个字符串参数是可选的。 希望这能回答你的问题。

“CheckUserInput”的示例:

 private bool CheckUserInput(string account, string password) { // your conditions... return true; } 

这是我的应用程序的代码:

  using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using LibXmlSettings.Settings; using Microsoft.ApplicationBlocks.Data; using System.Data.Sql; using System.Data.SqlClient; using System.Data.SqlTypes; using System.DirectoryServices; using System.IO; using System.Linq.Expressions; using System.Runtime.InteropServices; using System.DirectoryServices.AccountManagement; namespace GestionnaireDesPlugins public partial class Login : Form { public Login(string accountName, string accountPassword) { InitializeComponent(); } private void btnLogin_Click(object sender, EventArgs e) { using (var context = new PrincipalContext(ContextType.Domain, "Domain")) { using (var searcher = new PrincipalSearcher(new UserPrincipal(context))) { foreach (var result in searcher.FindAll()) { DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry; comboBox1.Items.Add(de.Properties["samAccountName"].Value); comboBox1.Sorted = true; } } } // Check if the user haven't chosen an account if (comboBox1.Text == "") { return; } // Check if the password TextBox is empty if (textBox1.Text == "") { return; } // Create a new method for checking the account and password, which returns a bool bool loginSuccess = CheckUserInput(comboBox1.Text.Trim(), textBox1.Text); if (loginSuccess) { // Create a new instance of your user-interface form. Give the account name and password // to it's constructor UserForm newForm = new UserForm(comboBox1.Text.Trim(), textBox1.Text.Trim())) // Show the created UserForm form newForm.Show(); // Close this login form this.Close(); } } } 

我解决了我想要的东西

 private void btnLogin_Click(object sender, EventArgs e) { try { LdapConnection connection = new LdapConnection("AD"); NetworkCredential credential = new NetworkCredential(txtboxlogin.Text, txtboxpass.Text); connection.Credential = credential; connection.Bind(); MessageBox.Show("You are log in"); Hide(); if (txtboxlogin.Text == "WantedAdminUser") { using (AdminForm form2 = new AdminForm()) form2.ShowDialog(); Show(); } else { using (user userform = new user()) userform.ShowDialog(); Show(); } } catch (LdapException lexc) { String error = lexc.ServerErrorMessage; MessageBox.Show("error account or password."); } catch (Exception exc) { MessageBox.Show(Convert.ToString(exc)); }