zoukankan      html  css  js  c++  java
  • Query Active Directory Users using C#[转]

    I've been dinking around in the System.DirectoryServices namespace lately trying to update user's in Active Directory. This particular namespace has 2 main component classes: DirectoryEntry and DirectorySearcher. After a couple of days (hence no posting) I have successfully accomplished the tasks of querying for and updating users.  I will share some basic functionality for looking up and verifying users in Active Directory to lay the foundation for those of you that are interested.  It might be useful to read up on LDAP to get a good understanding of what it is and how it works with Active Directory.

    Setting up the connection
    public static DirectoryEntry GetDirectoryEntry()
    {
       DirectoryEntry de = new DirectoryEntry();
       de.Path = "LDAP://OU=Domain,DC=YourDomain,DC=com";
       de.AuthenticationType = AuthenticationTypes.Secure;

       return de;
    }

    Does a User Exist?
    Before you update any user information it is probably a good idea to find out if they actually exist in the Active Directory.

    public bool UserExists(string username)
    {
       DirectoryEntry de = GetDirectoryEntry();
       DirectorySearcher deSearch = new DirectorySearcher();

       deSearch.SearchRoot = de;
       deSearch.Filter = "(&(objectClass=user) (cn=" + username + "))";

       SearchResultCollection results = deSearch.FindAll();

    return results.Count > 0;
    }

    private String FindName(String userAccount)
    {
       DirectoryEntry entry = GetDirectoryEntry();
       String account = userAccount.Replace(@"Domain\", "");

       try
       {
          DirectorySearcher search = new DirectorySearcher(entry);
          search.Filter = "(SAMAccountName=" + account + ")";
          search.PropertiesToLoad.Add("displayName");

          SearchResult result = search.FindOne();

          if (result != null)
          {
             return result.Properties["displayname"][0].ToString();
          }
          else
          {
             return "Unknown User";
          }
       }
       catch (Exception ex)
       {
          string debug = ex.Message;
          return "";
       }
    }

    The form I created has 2 textboxes (Username & Password) and a submit button. When the button is clicked all the events are fired and if everything checks out the user is updated in Active Directory.

    private void btnUpdate_Click(object sender, EventArgs e)
    {
       if (tbUser.Text != "" && tbPass.Text != "")
       {
          string username = tbUser.Text.ToString();
          string password = tbPass.Text.ToString();

          if (UserExists(FindName(username))
          {
             ModifyUser(FindName(username), username, password);
          }
       }
    }

    Modify User Information
    public void ModifyUser(string userDisplayName, string username, string password)
    {
       DirectoryEntry de = GetDirectoryEntry();
       de.Username = username;
       de.Password = password;

       DirectorySearcher ds = new DirectorySearcher(de);
       ds.Filter = ("(&(objectclass=user)(objectcategory=person)
                   (displayname=" + userDisplayName + "))");

       ds.SearchScope = SearchScope.Subtree;

       SearchResult results = ds.FindOne();

       if (results != null)
       {
          try
          {
             DirectoryEntry updateEntry = results.GetDirectoryEntry();
             updateEntry.Properties["department"].Value = "555";
             updateEntry.CommitChanges();
             updateEntry.Close();
          }
          catch (Exception ex)
          {
             tbError.Text = ex.ToString();
          }
       }
       de.Close();
    }

    Good luck! With a little patience you will find that Active Directory is quite fun to work with.  Also keep in mind that this is a very basic example.  When you master this you can start pulling data from external data sources, formatting, look them up in Active Directory and then update accordingly!

  • 相关阅读:
    在WCF中使用Flag Enumerations
    WCF开发教程资源收集
    [转]WCF 4 安全性和 WIF 简介
    Asp.Net Web API 2 官网菜鸟学习系列导航[持续更新中]
    Asp.Net Web API 2第十八课——Working with Entity Relations in OData
    Asp.Net Web API 2第十七课——Creating an OData Endpoint in ASP.NET Web API 2(OData终结点)
    Asp.Net Web API 2第十六课——Parameter Binding in ASP.NET Web API(参数绑定)
    Asp.Net Web API 2第十五课——Model Validation(模型验证)
    函数 生成器 生成器表达式
    函数的进阶
  • 原文地址:https://www.cnblogs.com/flyinthesky/p/1571964.html
Copyright © 2011-2022 走看看