2015/01/28

C#.Net 檢查Active Directory是否存在

強者我朋友需要,紀錄一下

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);
            }
       
        }
    }
}