How to install Active Directory && Connect to AD using C#

How to install Active Directory && Connect to AD using C#

 

using System;
using System.DirectoryServices.AccountManagement;
namespace AD1
{
    class Program
    {
        static void Main(string[] args)
        {
            ActiveDirectory ac = new ActiveDirectory();
            Console.WriteLine("Login : " + ac.Login("[email protected]", "x"));
            Console.WriteLine("Search For eramax : " + ac.Search("eramax"));
            Console.WriteLine("Search For [email protected] : " + ac.SearchByEmail("[email protected]"));
            Console.WriteLine("Print All Users in AD" ); ac.GetAllUsers();
            Console.ReadLine();
        }

    }
    public class ActiveDirectory
    {
        private static string LDAPServerIP = "x.x.x.x";
        private static string ADDomain = "domain.local";
        private static string ADUsername = "[email protected]";
        private static string ADPassword = "x";
        public bool Login(string username, string pass)
        {
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, LDAPServerIP , ADUsername, ADPassword))
            {
                bool userValid = ctx.ValidateCredentials(username, pass);
                return userValid;
            }
        }

        public string Search(string userName)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, LDAPServerIP, ADUsername, ADPassword);
            var user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, ADDomain + "\\" + userName);
            return user != null ? user.UserPrincipalName : null;
        }
        public string SearchByEmail(string userName)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, LDAPServerIP, ADUsername, ADPassword);
            var user = UserPrincipal.FindByIdentity(ctx, IdentityType.UserPrincipalName,  userName);
            return user != null ? user.UserPrincipalName : null;
        }
        public void GetAllUsers()
        {
            PrincipalContext domain = new PrincipalContext(ContextType.Domain, LDAPServerIP, ADUsername, ADPassword);
            PrincipalSearcher search = new PrincipalSearcher(new UserPrincipal(domain));
            foreach (UserPrincipal user in search.FindAll())
            {
                Console.WriteLine(user.DistinguishedName);
            }
        }

    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.