Code:
using System; using System.DirectoryServices.AccountManagement; using System.Windows.Forms; namespace TestAD { public partial class Form1 : Form { private String User { get { return System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1]; } } private String Domain { get { return textBox1.Text; } } public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { using (PrincipalContext context = new PrincipalContext(ContextType.Domain, Domain)) { using (UserPrincipal f = UserPrincipal.FindByIdentity(context, User)) { bool exists = f != null; if (exists) MessageBox.Show("存在"); else MessageBox.Show("不存在"); } } } catch (PrincipalServerDownException ex) { MessageBox.Show("AD連接失敗"); } catch (MultipleMatchesException ex) { MessageBox.Show(ex.Message); } } } }