c# 域操作实例 AD身份验证

 

domainName  域服務器名稱   例如 AD1.Domain.com.tw

ADPATH = LDAP://AD1.Domain.com.cn/DC= Domain,DC=com,DC=cn

 

 

private static DirectoryEntry GetDirectoryObject(string domainName, string adUser, string adPassword)

    {

        DirectoryEntry entry = new DirectoryEntry("LDAP://ad服務器名稱/DC=xxx,DC=com,DC=cn", adUser, adPassword, AuthenticationTypes.Secure);

        return entry;

    }

 

    public static DirectoryEntry GetDirectoryEntry(string domainName, string commonName, string password)

    {

        try

        {

            DirectoryEntry de = GetDirectoryObject(domainName, commonName, password);

            DirectorySearcher deSearch = new DirectorySearcher(de);

            deSearch.Filter = "(SAMAccountName=" + commonName + ")";

            deSearch.SearchScope = SearchScope.Subtree;

            SearchResult result = deSearch.FindOne();

            de = new DirectoryEntry(result.Path);

            return de;

        }

        catch(Exception e)

        {

            return null;

        }

    }

 

 


  1. 原來是LDAP要加上AD電腦名稱 DirectoryEntry objDirEnt = new DirectoryEntry("LDAP://AD1.Domain.com.tw/CN=王小明,OU=客服部,DC=Domain,DC=com,DC=cn","帳號","密碼");


    AD1.Domain.com.tw 域服務器名稱



  2. using System;  
  3. using System.DirectoryServices;  
  4.    
  5. namespace SystemFrameworks.Helper  
  6. {  
  7.      ///  
  8.      ///活动目录辅助类。封装一系列活动目录操作相关的方法。  
  9.      ///  
  10.      public sealed class ADHelper  
  11.      {  
  12.          ///  
  13.          ///域名  
  14.          ///  
  15.          private static string DomainName = "MyDomain";  
  16.          ///  
  17.          /// LDAP 地址  
  18.          ///  
  19.          private static string LDAPDomain = "DC=MyDomain,DC=local";  
  20.          ///  
  21.          /// LDAP绑定路径  
  22.          ///  
  23.          private static string ADPath = "LDAP://brooks.mydomain.local";  
  24.          ///  
  25.          ///登录帐号  
  26.          ///  
  27.          private static string ADUser = "Administrator";  
  28.          ///  
  29.          ///登录密码  
  30.          ///  
  31.          private static string ADPassword = "password";  
  32.          ///  
  33.          ///扮演类实例  
  34.          ///  
  35.          private static IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);  
  36.    
  37.          ///  
  38.          ///用户登录验证结果  
  39.          ///  
  40.          public enum LoginResult  
  41.          {  
  42.               ///  
  43.               ///正常登录  
  44.               ///  
  45.               LOGIN_USER_OK = 0,  
  46.               ///  
  47.               ///用户不存在  
  48.               ///  
  49.               LOGIN_USER_DOESNT_EXIST,  
  50.               ///  
  51.               ///用户帐号被禁用   t;
  52.               ///  
  53.               LOGIN_USER_ACCOUNT_INACTIVE,  
  54.               ///  
  55.               ///用户密码不正确  
  56.               ///  
  57.               LOGIN_USER_PASSWORD_INCORRECT  
  58.          }  
  59.    
  60.          ///  
  61.          ///用户属性定义标志  
  62.          ///  
  63.          public enum ADS_USER_FLAG_ENUM  
  64.          {  
  65.               ///  
  66.               ///登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。  
  67.               ///  
  68.               ADS_UF_SCRIPT = 0X0001,  
  69.               ///  
  70.               ///用户帐号禁用标志  
  71.               ///  
  72.               ADS_UF_ACCOUNTDISABLE = 0X0002,  
  73.               ///  
  74.               ///主文件夹标志  
  75.               ///  
  76.               ADS_UF_HOMEDIR_REQUIRED = 0X0008,  
  77.               ///  
  78.               ///过期标志  
  79.               ///  
  80.               ADS_UF_LOCKOUT = 0X0010,  
  81.               ///  
  82.               ///用户密码不是必须的  
  83.               ///  
  84.               ADS_UF_PASSWD_NOTREQD = 0X0020,  
  85.               ///  
  86.               ///密码不能更改标志  
  87.               ///  
  88.               ADS_UF_PASSWD_CANT_CHANGE = 0X0040,  
  89.               ///  
  90.               ///使用可逆的加密保存密码  
  91.               ///  
  92.               ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,  
  93.               ///  
  94.               ///本地帐号标志  
  95.               ///  
  96.               ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,  
  97.               ///  
  98.               ///普通用户的默认帐号类型  
  99.               ///  
  100.               ADS_UF_NORMAL_ACCOUNT = 0X0200,  
  101.               ///  
  102.               ///跨域的信任帐号标志  
  103.               ///  
  104.               ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,  
  105.               ///  
  106.               ///工作站信任帐号标志  
  107.               ///  
  108.               ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,  
  109.               ///  
  110.               ///服务器信任帐号标志  
  111.               ///  
  112.               ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,  
  113.               ///  
  114.               ///密码永不过期标志  
  115.               ///  
  116.               ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,  
  117.               ///  
  118.               /// MNS 帐号标志  
  119.               ///  
  120.               ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,  
  121.               ///  
  122.               ///交互式登录必须使用智能卡  
  123.               ///  
  124.               ADS_UF_SMARTCARD_REQUIRED = 0X40000,  
  125.               ///  
  126.               ///当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任  
  127.               ///  
  128.               ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,  
  129.               ///  
  130.               ///当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托  
  131.               ///  
  132.               ADS_UF_NOT_DELEGATED = 0X100000,  
  133.               ///  
  134.               ///此帐号需要 DES 加密类型  
  135.               ///  
  136.               ADS_UF_USE_DES_KEY_ONLY = 0X200000,  
  137.               ///  
  138.               ///不要进行 Kerberos 预身份验证  
  139.               ///  
  140.               ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,  
  141.               ///  
  142.               ///用户密码过期标志  
  143.               ///  
  144.               ADS_UF_PASSWORD_EXPIRED = 0X800000,  
  145.               ///  
  146.               ///用户帐号可委托标志  
  147.               ///  
  148.               ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000  
  149.          }  
  150.    
  151.          public ADHelper()  
  152.          {  
  153.               //  
  154.          }  
  155.   
  156.          #region GetDirectoryObject  
  157.    
  158.          ///  
  159.          ///获得DirectoryEntry对象实例,以管理员登陆AD  
  160.          ///  
  161.          ///  
  162.          private static DirectoryEntry GetDirectoryObject()  
  163.          {  
  164.               DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);  
  165.               return entry;  
  166.          }  
  167.    
  168.          ///  
  169.          ///根据指定用户名和密码获得相应DirectoryEntry实体  
  170.          ///  
  171.          ///  
  172.          ///  
  173.          ///  
  174.          private static DirectoryEntry GetDirectoryObject(string userName, string password)  
  175.          {  
  176.               DirectoryEntry entry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.None);  
  177.               return entry;  
  178.          }  
  179.    
  180.          ///  
  181.          /// i.e. /CN=Users,DC=creditsights, DC=cyberelves, DC=Com  
  182.          ///  
  183.          ///  
  184.          ///  
  185.          private static DirectoryEntry GetDirectoryObject(string domainReference)  
  186.          {  
  187.               DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword, AuthenticationTypes.Secure);  
  188.               return entry;  
  189.          }  
  190.    
  191.          ///  
  192.          ///获得以UserName,Password创建的DirectoryEntry  
  193.          ///  
  194.          ///  
  195.          ///  
  196.          ///  
  197.          ///  
  198.          private static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password)  
  199.          {  
  200.               DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, userName, password, AuthenticationTypes.Secure);  
  201.               return entry;  
  202.          }  
  203.   
  204.          #endregion  
  205.    
  206.          #region GetDirectoryEntry  
  207.    
  208.          ///  
  209.          ///根据用户公共名称取得用户的 对象  
  210.          ///  
  211.          ///  
  212. 用户公共名称   
  213.          ///如果找到该用户,则返回用户的 对象;否则返回 null  
  214.          public static DirectoryEntry GetDirectoryEntry(string commonName)  
  215.          {  
  216.               DirectoryEntry de = GetDirectoryObject();  
  217.               DirectorySearcher deSearch = new DirectorySearcher(de);  
  218.               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";  
  219.               deSearch.SearchScope = SearchScope.Subtree;  
  220.    
  221.               try  
  222.               {  
  223.                    SearchResult result = deSearch.FindOne();  
  224.                    de = new DirectoryEntry(result.Path);  
  225.                    return de;  
  226.               }  
  227.               catch  
  228.               {  
  229.                    return null;  
  230.               }  
  231.          }  
  232.    
  233.          ///  
  234.          ///根据用户公共名称和密码取得用户的 对象。  
  235.          ///  
  236.          ///  
  237. 用户公共名称   
  238.          ///  
  239. 用户密码   
  240.          ///如果找到该用户,则返回用户的 对象;否则返回 null  
  241.          public static DirectoryEntry GetDirectoryEntry(string commonName, string password)  
  242.          {  
  243.               DirectoryEntry de = GetDirectoryObject(commonName, password);  
  244.               DirectorySearcher deSearch = new DirectorySearcher(de);  
  245.               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";  
  246.               deSearch.SearchScope = SearchScope.Subtree;  
  247.    
  248.               try  
  249.               {  
  250.                    SearchResult result = deSearch.FindOne();  
  251.                    de = new DirectoryEntry(result.Path);  
  252.                    return de;  
  253.               }  
  254.               catch  
  255.               {  
  256.                    return null;  
  257.               }  
  258.          }  
  259.    
  260.          ///  
  261.          ///根据用户帐号称取得用户的 对象  
  262.          ///  
  263.          ///  
  264. 用户帐号名   
  265.          ///如果找到该用户,则返回用户的 对象;否则返回 null  
  266.          public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)  
  267.          {  
  268.               DirectoryEntry de = GetDirectoryObject();  
  269.               DirectorySearcher deSearch = new DirectorySearcher(de);  
  270.               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";  
  271.               deSearch.SearchScope = SearchScope.Subtree;  
  272.    
  273.               try  
  274.               {  
  275.                    SearchResult result = deSearch.FindOne();  
  276.                    de = new DirectoryEntry(result.Path);  
  277.                    return de;  
  278.               }  
  279.               catch  
  280.               {  
  281.                    return null;  
  282.               }  
  283.          }  
  284.    
  285.          ///  
  286.          ///根据用户帐号和密码取得用户的 对象  
  287.          ///  
  288.          ///  
  289. 用户帐号名   
  290.          ///  
  291. 用户密码   
  292.          ///如果找到该用户,则返回用户的 对象;否则返回 null  
  293.          public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)  
  294.          {  
  295.               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);  
  296.               if (de != null)  
  297.               {  
  298.                    string commonName = de.Properties["cn"][0].ToString();  
  299.    
  300.                    if (GetDirectoryEntry(commonName, password) != null)  
  301.                        return GetDirectoryEntry(commonName, password);  
  302.                    else  
  303.                        return null;  
  304.               }  
  305.               else  
  306.               {  
  307.                    return null;  
  308.               }  
  309.          }  
  310.    
  311.          ///  
  312.          ///根据组名取得用户组的 对象  
  313.          ///  
  314.          ///  
  315. 组名   
  316.          ///  
  317.          public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)  
  318.          {  
  319.               DirectoryEntry de = GetDirectoryObject();  
  320.               DirectorySearcher deSearch = new DirectorySearcher(de);  
  321.               deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";  
  322.               deSearch.SearchScope = SearchScope.Subtree;  
  323.    
  324.               try  
  325.               {  
  326.                    SearchResult result = deSearch.FindOne();  
  327.                    de = new DirectoryEntry(result.Path);  
  328.                    return de;  
  329.               }  
  330.               catch  
  331.               {  
  332.                    return null;  
  333.               }  
  334.          }  
  335.   
  336.          #endregion  
  337.    
  338.          #region GetProperty  
  339.    
  340.          ///  
  341.          ///获得指定 指定属性名对应的值  
  342.          ///  
  343.          ///  
  344.          ///  
  345. 属性名称   
  346.          ///属性值  
  347.          public static string GetProperty(DirectoryEntry de, string propertyName)  
  348.          {  
  349.               if(de.Properties.Contains(propertyName))  
  350.               {  
  351.                    return de.Properties[propertyName][0].ToString() ;  
  352.               }  
  353.               else  
  354.               {  
  355.                    return string.Empty;  
  356.               }  
  357.          }  
  358.    
  359.          ///  
  360.          ///获得指定搜索结果 中指定属性名对应的值  
  361.          ///  
  362.          ///  
  363.          ///  
  364. 属性名称   
  365.          ///属性值  
  366.          public static string GetProperty(SearchResult searchResult, string propertyName)  
  367.          {  
  368.               if(searchResult.Properties.Contains(propertyName))  
  369.               {  
  370.                    return searchResult.Properties[propertyName][0].ToString() ;  
  371.               }  
  372.               else  
  373.               {  
  374.                    return string.Empty;  
  375.               }  
  376.          }  
  377.   
  378.          #endregion  
  379.    
  380.          ///  
  381.          ///设置指定 的属性值  
  382.          ///  
  383.          ///  
  384.          ///  
  385. 属性名称   
  386.          ///  
  387. 属性值   
  388.          public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)  
  389.          {  
  390.               if(propertyValue != string.Empty || propertyValue != "" || propertyValue != null)  
  391.               {  
  392.                    if(de.Properties.Contains(propertyName))  
  393.                    {  
  394.                        de.Properties[propertyName][0] = propertyValue;   
  395.                    }  
  396.                    else  
  397.                    {  
  398.                        de.Properties[propertyName].Add(propertyValue);  
  399.                    }  
  400.               }  
  401.          }  
  402.    
  403.          ///  
  404.          ///创建新的用户  
  405.          ///  
  406.          ///  
  407. DN 位置。例如:OU=共享平台 或 CN=Users   
  408.          ///  
  409. 公共名称   
  410.          ///  
  411. 帐号   
  412.          ///  
  413. 密码   
  414.          ///  
  415.          public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password)  
  416.          {  
  417.               DirectoryEntry entry = GetDirectoryObject();  
  418.               DirectoryEntry subEntry = entry.Children.Find(ldapDN);  
  419.               DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user");  
  420.               deUser.Properties["sAMAccountName"].Value = sAMAccountName;  
  421.               deUser.CommitChanges();  
  422.               ADHelper.EnableUser(commonName);  
  423.               ADHelper.SetPassword(commonName, password);  
  424.               deUser.Close();  
  425.               return deUser;  
  426.          }  
  427.    
  428.          ///  
  429.          ///创建新的用户。默认创建在 Users 单元下。  
  430.          ///  
  431.          ///  
  432. 公共名称   
  433.          ///  
  434. 帐号   
  435.          ///  
  436. 密码   
  437.          ///  
  438.          public static DirectoryEntry CreateNewUser(string commonName, string sAMAccountName, string password)  
  439.          {  
  440.               return CreateNewUser("CN=Users", commonName, sAMAccountName, password);  
  441.          }  
  442.    
  443.          ///  
  444.          ///判断指定公共名称的用户是否存在  
  445.          ///  
  446.          ///  
  447. 用户公共名称   
  448.          ///如果存在,返回 true;否则返回 false  
  449.          public static bool IsUserExists(string commonName)  
  450.          {  
  451.               DirectoryEntry de = GetDirectoryObject();  
  452.               DirectorySearcher deSearch = new DirectorySearcher(de);  
  453.               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";       // LDAP 查询串  
  454.               SearchResultCollection results = deSearch.FindAll();  
  455.    
  456.               if (results.Count == 0)  
  457.                    return false;  
  458.               else  
  459.                    return true;  
  460.          }  
  461.    
  462.          ///  
  463.          ///判断用户帐号是否激活  
  464.          ///  
  465.          ///  
  466. 用户帐号属性控制器   
  467.          ///如果用户帐号已经激活,返回 true;否则返回 false  
  468.          public static bool IsAccountActive(int userAccountControl)  
  469.          {  
  470.               int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE);  
  471.               int flagExists = userAccountControl & userAccountControl_Disabled;  
  472.    
  473.               if (flagExists > 0)  
  474.                    return false;  
  475.               else  
  476.                    return true;  
  477.          }  
  478.    
  479.          ///  
  480.          ///判断用户与密码是否足够以满足身份验证进而登录  
  481.          ///  
  482.          ///  
  483. 用户公共名称   
  484.          ///  
  485. 密码   
  486.          ///如能可正常登录,则返回 true;否则返回 false  
  487.          public static LoginResult Login(string commonName, string password)  
  488.          {  
  489.               DirectoryEntry de = GetDirectoryEntry(commonName);  
  490.    
  491.               if (de != null)  
  492.               {  
  493.                    // 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。  
  494.                    int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);  
  495.                    de.Close();  
  496.    
  497.                    if (!IsAccountActive(userAccountControl))  
  498.                        return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;  
  499.    
  500.                    if (GetDirectoryEntry(commonName, password) != null)  
  501.                        return LoginResult.LOGIN_USER_OK;  
  502.                    else  
  503.                        return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;  
  504.               }  
  505.               else  
  506.               {  
  507.                    return LoginResult.LOGIN_USER_DOESNT_EXIST;   
  508.               }  
  509.          }  
  510.    
  511.          ///  
  512.          ///判断用户帐号与密码是否足够以满足身份验证进而登录  
  513.          ///  
  514.          ///  
  515. 用户帐号   
  516.          ///  
  517. 密码   
  518.          ///如能可正常登录,则返回 true;否则返回 false  
  519.          public static LoginResult LoginByAccount(string sAMAccountName, string password)  
  520.          {  
  521.               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);  
  522.                      
  523.               if (de != null)  
  524.               {  
  525.                    // 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。  
  526.                    int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);  
  527.                    de.Close();  
  528.    
  529.                    if (!IsAccountActive(userAccountControl))  
  530.                        return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;  
  531.    
  532.                    if (GetDirectoryEntryByAccount(sAMAccountName, password) != null)  
  533.                        return LoginResult.LOGIN_USER_OK;  
  534.                    else  
  535.                        return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;  
  536.               }  
  537.               else  
  538.               {  
  539.                    return LoginResult.LOGIN_USER_DOESNT_EXIST;   
  540.               }  
  541.          }  
  542.    
  543.          ///  
  544.          ///设置用户密码,管理员可以通过它来修改指定用户的密码。  
  545.          ///  
  546.          ///  
  547. 用户公共名称   
  548.          ///  
  549. 用户新密码   
  550.          public static void SetPassword(string commonName, string newPassword)  
  551.          {  
  552.               DirectoryEntry de = GetDirectoryEntry(commonName);  
  553.                 
  554.               // 模拟超级管理员,以达到有权限修改用户密码  
  555.               impersonate.BeginImpersonate();  
  556.               de.Invoke("SetPassword"new object[]{newPassword});  
  557.               impersonate.StopImpersonate();  
  558.    
  559.               de.Close();  
  560.          }  
  561.    
  562.          ///  
  563.          ///设置帐号密码,管理员可以通过它来修改指定帐号的密码。  
  564.          ///  
  565.          ///  
  566. 用户帐号   
  567.          ///  
  568. 用户新密码   
  569.          public static void SetPasswordByAccount(string sAMAccountName, string newPassword)  
  570.          {  
  571.               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);  
  572.    
  573.               // 模拟超级管理员,以达到有权限修改用户密码  
  574.               IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);  
  575.               impersonate.BeginImpersonate();  
  576.               de.Invoke("SetPassword"new object[]{newPassword});  
  577.               impersonate.StopImpersonate();  
  578.    
  579.               de.Close();  
  580.          }  
  581.    
  582.          ///  
  583.          ///修改用户密码  
  584.          ///  
  585.          ///  
  586. 用户公共名称   
  587.          ///  
  588. 旧密码   
  589.          ///  
  590. 新密码   
  591.          public static void ChangeUserPassword (string commonName, string oldPassword, string newPassword)  
  592.          {  
  593.               // to-do: 需要解决密码策略问题  
  594.               DirectoryEntry oUser = GetDirectoryEntry(commonName);  
  595.               oUser.Invoke("ChangePassword"new Object[]{oldPassword, newPassword});  
  596.               oUser.Close();  
  597.          }  
  598.    
  599.          ///  
  600.          ///启用指定公共名称的用户  
  601.          ///  
  602.          ///  
  603. 用户公共名称   
  604.          public static void EnableUser(string commonName)  
  605.          {  
  606.               EnableUser(GetDirectoryEntry(commonName));  
  607.          }  
  608.    
  609.          ///  
  610.          ///启用指定 的用户  
  611.          ///  
  612.          ///  
  613.          public static void EnableUser(DirectoryEntry de)  
  614.          {  
  615.               impersonate.BeginImpersonate();  
  616.               de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;  
  617.               de.CommitChanges();  
  618.               impersonate.StopImpersonate();  
  619.               de.Close();  
  620.          }  
  621.    
  622.          ///  
  623.          ///禁用指定公共名称的用户  
  624.          ///  
  625.          ///  
  626. 用户公共名称   
  627.          public static void DisableUser(string commonName)  
  628.          {  
  629.               DisableUser(GetDirectoryEntry(commonName));  
  630.          }  
  631.    
  632.          ///  
  633.          ///禁用指定 的用户  
  634.          ///  
  635.          ///  
  636.          public static void DisableUser(DirectoryEntry de)  
  637.          {  
  638.               impersonate.BeginImpersonate();  
  639.               de.Properties["userAccountControl"][0]=ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;  
  640.               de.CommitChanges();  
  641.               impersonate.StopImpersonate();  
  642.               de.Close();  
  643.          }  
  644.    
  645.          ///  
  646.          ///将指定的用户添加到指定的组中。默认为 Users 下的组和用户。  
  647.          ///  
  648.          ///  
  649. 用户公共名称   
  650.          ///  
  651. 组名   
  652.          public static void AddUserToGroup(string userCommonName, string groupName)  
  653.           {  
  654.               DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);  
  655.               DirectoryEntry oUser = GetDirectoryEntry(userCommonName);  
  656.                 
  657.               impersonate.BeginImpersonate();  
  658.               oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);  
  659.               oGroup.CommitChanges();  
  660.               impersonate.StopImpersonate();  
  661.    
  662.               oGroup.Close();  
  663.               oUser.Close();  
  664.          }  
  665.    
  666.          ///  
  667.          ///将用户从指定组中移除。默认为 Users 下的组和用户。  
  668.          ///  
  669.          ///  
  670. 用户公共名称   
  671.          ///  
  672. 组名   
  673.          public static void RemoveUserFromGroup(string userCommonName, string groupName)  
  674.          {  
  675.               DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);  
  676.               DirectoryEntry oUser = GetDirectoryEntry(userCommonName);  
  677.                 
  678.               impersonate.BeginImpersonate();  
  679.               oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);  
  680.               oGroup.CommitChanges();  
  681.               impersonate.StopImpersonate();  
  682.    
  683.               oGroup.Close();  
  684.               oUser.Close();  
  685.          }  
  686.    
  687.      }  
  688.    
  689.      ///  
  690.      ///用户模拟角色类。实现在程序段内进行用户角色模拟。  
  691.      ///  
  692.      public class IdentityImpersonation  
  693.      {  
  694.          [DllImport("advapi32.dll", SetLastError=true)]  
  695.          public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);  
  696.    
  697.          [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]  
  698.          public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);  
  699.    
  700.          [DllImport("kernel32.dll", CharSet=CharSet.Auto)]  
  701.          public extern static bool CloseHandle(IntPtr handle);  
  702.    
  703.          // 要模拟的用户的用户名、密码、域(机器名)  
  704.          private String _sImperUsername;  
  705.          private String _sImperPassword;  
  706.          private String _sImperDomain;  
  707.          // 记录模拟上下文  
  708.          private WindowsImpersonationContext _imperContext;  
  709.          private IntPtr _adminToken;  
  710.          private IntPtr _dupeToken;  
  711.          // 是否已停止模拟  
  712.          private Boolean _bClosed;  
  713.    
  714.          ///  
  715.          ///构造函数  
  716.          ///  
  717.          ///  
  718. 所要模拟的用户的用户名   
  719.          ///  
  720. 所要模拟的用户的密码   
  721.          ///  
  722. 所要模拟的用户所在的域   
  723.          public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)   
  724.          {  
  725.               _sImperUsername = impersonationUsername;  
  726.               _sImperPassword = impersonationPassword;  
  727.               _sImperDomain = impersonationDomain;  
  728.    
  729.               _adminToken = IntPtr.Zero;  
  730.               _dupeToken = IntPtr.Zero;  
  731.               _bClosed = true;  
  732.          }  
  733.    
  734.          ///  
  735.          ///析构函数  
  736.          ///  
  737.          ~IdentityImpersonation()   
  738.          {  
  739.               if(!_bClosed)   
  740.               {  
  741.                    StopImpersonate();  
  742.               }  
  743.          }  
  744.    
  745.          ///  
  746.          ///开始身份角色模拟。  
  747.          ///  
  748.          ///  
  749.          public Boolean BeginImpersonate()   
  750.          {  
  751.               Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken);  
  752.                           
  753.               if(!bLogined)   
  754.               {  
  755.                    return false;  
  756.               }  
  757.    
  758.               Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);  
  759.    
  760.               if(!bDuped)   
  761.               {  
  762.                    return false;  
  763.               }  
  764.    
  765.               WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);  
  766.               _imperContext = fakeId.Impersonate();  
  767.    
  768.               _bClosed = false;  
  769.    
  770.               return true;  
  771.          }  
  772.    
  773.          ///  
  774.          ///停止身分角色模拟。  
  775.          ///  
  776.          public void StopImpersonate()   
  777.          {  
  778.               _imperContext.Undo();  
  779.               CloseHandle(_dupeToken);  
  780.               CloseHandle(_adminToken);  
  781.               _bClosed = true;  
  782.          }  
  783.      }  
  784. }  
  785. =====================================================  
  786.   
  787. 简单的应用  
  788.   
  789. [WebMethod]  
  790.   public string IsAuthenticated(string UserID,string Password)  
  791.   {  
  792.             string _path = "LDAP://" + adm + "/DC=lamda,DC=com,DC=cn";//"LDAP://172.75.200.1/DC=名字,DC=com,DC=cn";  
  793.    string _filterAttribute=null;  
  794.     
  795.    DirectoryEntry entry = new DirectoryEntry(_path,UserID,Password);  
  796.      
  797.    try  
  798.    {  
  799.     //Bind to the native AdsObject to force authentication.  
  800.     DirectorySearcher search = new DirectorySearcher(entry);  
  801.     search.Filter = "(SAMAccountName=" + UserID + ")";  
  802.     SearchResult result = search.FindOne();  
  803.       
  804.     if(null == result)  
  805.     {  
  806.      _filterAttribute="登录失败: 未知的用户名或错误密码.";  
  807.     }  
  808.     else  
  809.     {  
  810.      _filterAttribute="true";  
  811.     }  
  812.      
  813.    }  
  814.    catch (Exception ex)  
  815.    {  
  816. //    if(ex.Message.StartsWith("该服务器不可操作"))   
  817. //    {  
  818. //     string mail = ADO.GetConnString("mail");  
  819. //     entry.Path = "LDAP://"+mail+"/OU=名字,DC=it2004,DC=gree,DC=com,DC=cn";  
  820. //     try  
  821. //     {   
  822. //      DirectorySearcher search = new DirectorySearcher(entry);  
  823. //      search.Filter = "(SAMAccountName=" + UserID + ")";  
  824. //      SearchResult result = search.FindOne();  
  825. //  
  826. //      if(null == result)  
  827. //      {  
  828. //       _filterAttribute="登录失败: 未知的用户名或错误密码.";  
  829. //      }  
  830. //      else  
  831. //      {  
  832. //       _filterAttribute="true";  
  833. //      }  
  834. //      return _filterAttribute;  
  835. //     
  836. //     }  
  837. //     catch (Exception ex1)  
  838. //     {  
  839. //      return ex1.Message;  
  840. //     }  
  841. //       
  842. //    }  
  843. //    else  
  844.      return ex.Message;  
  845.    }  
  846.    return _filterAttribute;  
  847.   }  
  848.   [WebMethod]  
  849.   public string[] LDAPMessage(string UserID)  
  850.   {  
  851.    string _path = "LDAP://"+adm+"/DC=it2004,DC=名字,DC=com,DC=cn";  
  852.    string[] _filterAttribute=new string[5];  
  853.    string[] msg = {"samaccountname","displayname","department","company"};  
  854.   
  855.    DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813");  
  856.   
  857.      
  858.    try  
  859.    {   
  860.   
  861.   
  862.     Object obj = entry.NativeObject;  
  863.       
  864.     DirectorySearcher search = new DirectorySearcher(entry);  
  865.     search.Filter = "(SAMAccountName=" + UserID + ")";  
  866.     SearchResult result = search.FindOne();  
  867.   
  868.       
  869.     if(null == result)  
  870.     {  
  871.      _filterAttribute[0]="登录失败: 未知的用户名或错误密码.";  
  872.     }  
  873.     else  
  874.     {  
  875.      _filterAttribute[0]="true";    
  876.      for(int propertyCounter = 1; propertyCounter < 5; propertyCounter++)  
  877.      {  
  878.          
  879.       if(propertyCounter==4 &&  result.Properties[msg[propertyCounter-1]][0]==null)  
  880.        break;  
  881.       _filterAttribute[propertyCounter]=result.Properties[msg[propertyCounter-1]][0].ToString();  
  882.         
  883.      }  
  884.     }  
  885.      
  886.    }  
  887.    catch (Exception ex)  
  888.    {  
  889.     //_filterAttribute[0]=ex.Message;  
  890.    }  
  891.    return _filterAttribute;  
  892.   }  
  893.   [WebMethod]  
  894.   public string[] AllMembers()   
  895.   {  
  896.      
  897.    string[] msg;  
  898.    string _path = "LDAP://名字";  
  899.   
  900.    DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813");  
  901.      
  902.    
  903.    //Bind to the native AdsObject to force authentication.  
  904.    Object obj = entry.NativeObject;  
  905.   
  906.    System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);  
  907.    mySearcher.Filter = "(SAMAccountName=180037)";  
  908.    msg=new string[mySearcher.FindAll().Count];  
  909.    int i=0;  
  910.    foreach(System.DirectoryServices.SearchResult result in mySearcher.FindAll())   
  911.    {  
  912.     msg[i++]=result.Path;  
  913.    }  
  914.    return msg;  
  915.   }  
  916.    
  917.  }  

 

 

//***********************************************************************

//***********************************************************************

//***********************************************************************

 

 

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.DirectoryServices;

 

namespace change

{

 /// <summary>

 /// Form1 的摘要说明。

 /// </summary>

 public class Form1 : System.Windows.Forms.Form

 {

  private System.Windows.Forms.ComboBox comboBox2;

  private System.Windows.Forms.Label label3;

  private System.Windows.Forms.ComboBox comboBox1;

  private System.Windows.Forms.Label label2;

  string str="";

  string strErr="";

  string strManager="";

  private System.Windows.Forms.Label label1;

  private System.Windows.Forms.Label label4;

  private System.Windows.Forms.Button button1;

  private System.Windows.Forms.TextBox textBox1;

  private System.Windows.Forms.TextBox textBox2;

  private System.Windows.Forms.TextBox textBox3;

  private System.Windows.Forms.CheckBox checkBox1;

  private System.Windows.Forms.CheckBox checkBox2;

  private System.Windows.Forms.CheckBox checkBox3;

  private System.Windows.Forms.Label label5;

  private System.Windows.Forms.TextBox textBox4;

  private System.Windows.Forms.ComboBox comboBox3;

  private System.Windows.Forms.Label label6;

  private System.Windows.Forms.ComboBox comboBox4;

  private System.Windows.Forms.Label label7;

  private System.Windows.Forms.ComboBox comboBox5;

  private System.Windows.Forms.Label label8;

  private System.Windows.Forms.ComboBox comboBox6;

  private System.Windows.Forms.Label label9;

  /// <summary>

  /// 必需的设计器变量。

  /// </summary>

  private System.ComponentModel.Container components = null;

 

  public Form1()

  {

   //

   // Windows 窗体设计器支持所必需的

   //

   InitializeComponent();

 

   //

   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

   //

  }

 

  /// <summary>

  /// 清理所有正在使用的资源。

  /// </summary>

  protected override void Dispose( bool disposing )

  {

   if( disposing )

   {

    if (components != null) 

    {

     components.Dispose();

    }

   }

   base.Dispose( disposing );

  }

 

  #region Windows 窗体设计器生成的代码

  /// <summary>

  /// 设计器支持所需的方法 - 不要使用代码编辑器修改

  /// 此方法的内容。

  /// </summary>

  private void InitializeComponent()

  {

   this.comboBox2 = new System.Windows.Forms.ComboBox();

   this.label3 = new System.Windows.Forms.Label();

   this.comboBox1 = new System.Windows.Forms.ComboBox();

   this.label2 = new System.Windows.Forms.Label();

   this.label1 = new System.Windows.Forms.Label();

   this.label4 = new System.Windows.Forms.Label();

   this.button1 = new System.Windows.Forms.Button();

   this.textBox1 = new System.Windows.Forms.TextBox();

   this.textBox2 = new System.Windows.Forms.TextBox();

   this.textBox3 = new System.Windows.Forms.TextBox();

   this.checkBox1 = new System.Windows.Forms.CheckBox();

   this.checkBox2 = new System.Windows.Forms.CheckBox();

   this.checkBox3 = new System.Windows.Forms.CheckBox();

   this.label5 = new System.Windows.Forms.Label();

   this.textBox4 = new System.Windows.Forms.TextBox();

   this.comboBox3 = new System.Windows.Forms.ComboBox();

   this.label6 = new System.Windows.Forms.Label();

   this.comboBox4 = new System.Windows.Forms.ComboBox();

   this.label7 = new System.Windows.Forms.Label();

   this.comboBox5 = new System.Windows.Forms.ComboBox();

   this.label8 = new System.Windows.Forms.Label();

   this.comboBox6 = new System.Windows.Forms.ComboBox();

   this.label9 = new System.Windows.Forms.Label();

   this.SuspendLayout();

   // 

   // comboBox2

   // 

   this.comboBox2.Location = new System.Drawing.Point(416, 16);

   this.comboBox2.Name = "comboBox2";

   this.comboBox2.Size = new System.Drawing.Size(121, 20);

   this.comboBox2.TabIndex = 10;

   this.comboBox2.SelectedIndexChanged += new System.EventHandler(this.comboBox2_SelectedIndexChanged);

   // 

   // label3

   // 

   this.label3.Location = new System.Drawing.Point(320, 20);

   this.label3.Name = "label3";

   this.label3.Size = new System.Drawing.Size(80, 16);

   this.label3.TabIndex = 9;

   this.label3.Text = "选择部门(OU)";

   // 

   // comboBox1

   // 

   this.comboBox1.Location = new System.Drawing.Point(144, 16);

   this.comboBox1.Name = "comboBox1";

   this.comboBox1.Size = new System.Drawing.Size(121, 20);

   this.comboBox1.TabIndex = 8;

   this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);

   // 

   // label2

   // 

   this.label2.AutoSize = true;

   this.label2.Location = new System.Drawing.Point(40, 19);

   this.label2.Name = "label2";

   this.label2.Size = new System.Drawing.Size(79, 17);

   this.label2.TabIndex = 7;

   this.label2.Text = "选择公司(OU)";

   // 

   // label1

   // 

   this.label1.Location = new System.Drawing.Point(48, 128);

   this.label1.Name = "label1";

   this.label1.Size = new System.Drawing.Size(72, 23);

   this.label1.TabIndex = 11;

   this.label1.Text = "新公司名称";

   // 

   // label4

   // 

   this.label4.Location = new System.Drawing.Point(328, 128);

   this.label4.Name = "label4";

   this.label4.Size = new System.Drawing.Size(72, 23);

   this.label4.TabIndex = 12;

   this.label4.Text = "新部门名称";

   // 

   // button1

   // 

   this.button1.Location = new System.Drawing.Point(376, 376);

   this.button1.Name = "button1";

   this.button1.TabIndex = 15;

   this.button1.Text = "开始处理";

   this.button1.Click += new System.EventHandler(this.button1_Click);

   // 

   // textBox1

   // 

   this.textBox1.Location = new System.Drawing.Point(144, 128);

   this.textBox1.Name = "textBox1";

   this.textBox1.Size = new System.Drawing.Size(120, 21);

   this.textBox1.TabIndex = 16;

   this.textBox1.Text = "";

   // 

   // textBox2

   // 

   this.textBox2.Location = new System.Drawing.Point(416, 128);

   this.textBox2.Name = "textBox2";

   this.textBox2.Size = new System.Drawing.Size(120, 21);

   this.textBox2.TabIndex = 17;

   this.textBox2.Text = "";

   // 

   // textBox3

   // 

   this.textBox3.Location = new System.Drawing.Point(32, 232);

   this.textBox3.Multiline = true;

   this.textBox3.Name = "textBox3";

   this.textBox3.ReadOnly = true;

   this.textBox3.ScrollBars = System.Windows.Forms.ScrollBars.Both;

   this.textBox3.Size = new System.Drawing.Size(504, 120);

   this.textBox3.TabIndex = 18;

   this.textBox3.Text = "";

   // 

   // checkBox1

   // 

   this.checkBox1.Location = new System.Drawing.Point(64, 192);

   this.checkBox1.Name = "checkBox1";

   this.checkBox1.TabIndex = 20;

   this.checkBox1.Text = "修改公司名称";

   // 

   // checkBox2

   // 

   this.checkBox2.Location = new System.Drawing.Point(200, 192);

   this.checkBox2.Name = "checkBox2";

   this.checkBox2.TabIndex = 21;

   this.checkBox2.Text = "修改部门名称";

   // 

   // checkBox3

   // 

   this.checkBox3.Location = new System.Drawing.Point(336, 192);

   this.checkBox3.Name = "checkBox3";

   this.checkBox3.TabIndex = 22;

   this.checkBox3.Text = "修改部门领导";

   // 

   // label5

   // 

   this.label5.AutoSize = true;

   this.label5.Location = new System.Drawing.Point(40, 160);

   this.label5.Name = "label5";

   this.label5.Size = new System.Drawing.Size(79, 17);

   this.label5.TabIndex = 19;

   this.label5.Text = "新的部门领导";

   // 

   // textBox4

   // 

   this.textBox4.Location = new System.Drawing.Point(144, 160);

   this.textBox4.Name = "textBox4";

   this.textBox4.Size = new System.Drawing.Size(392, 21);

   this.textBox4.TabIndex = 23;

   this.textBox4.Text = "请输入新领导的姓名全拼(域帐号)";

   // 

   // comboBox3

   // 

   this.comboBox3.Location = new System.Drawing.Point(144, 48);

   this.comboBox3.Name = "comboBox3";

   this.comboBox3.Size = new System.Drawing.Size(121, 20);

   this.comboBox3.TabIndex = 25;

   this.comboBox3.SelectedIndexChanged += new System.EventHandler(this.comboBox3_SelectedIndexChanged);

   // 

   // label6

   // 

   this.label6.AutoSize = true;

   this.label6.Location = new System.Drawing.Point(4, 51);

   this.label6.Name = "label6";

   this.label6.Size = new System.Drawing.Size(116, 17);

   this.label6.TabIndex = 24;

   this.label6.Text = "选择二级子部门(OU)";

   // 

   // comboBox4

   // 

   this.comboBox4.Location = new System.Drawing.Point(416, 48);

   this.comboBox4.Name = "comboBox4";

   this.comboBox4.Size = new System.Drawing.Size(121, 20);

   this.comboBox4.TabIndex = 27;

   this.comboBox4.SelectedIndexChanged += new System.EventHandler(this.comboBox4_SelectedIndexChanged);

   // 

   // label7

   // 

   this.label7.AutoSize = true;

   this.label7.Location = new System.Drawing.Point(284, 51);

   this.label7.Name = "label7";

   this.label7.Size = new System.Drawing.Size(116, 17);

   this.label7.TabIndex = 26;

   this.label7.Text = "选择三级子部门(OU)";

   // 

   // comboBox5

   // 

   this.comboBox5.Location = new System.Drawing.Point(416, 80);

   this.comboBox5.Name = "comboBox5";

   this.comboBox5.Size = new System.Drawing.Size(121, 20);

   this.comboBox5.TabIndex = 31;

   this.comboBox5.SelectedIndexChanged += new System.EventHandler(this.comboBox5_SelectedIndexChanged);

   // 

   // label8

   // 

   this.label8.Location = new System.Drawing.Point(280, 84);

   this.label8.Name = "label8";

   this.label8.Size = new System.Drawing.Size(120, 16);

   this.label8.TabIndex = 30;

   this.label8.Text = "选择级五子部门(OU)";

   // 

   // comboBox6

   // 

   this.comboBox6.Location = new System.Drawing.Point(144, 80);

   this.comboBox6.Name = "comboBox6";

   this.comboBox6.Size = new System.Drawing.Size(121, 20);

   this.comboBox6.TabIndex = 29;

   this.comboBox6.SelectedIndexChanged += new System.EventHandler(this.comboBox6_SelectedIndexChanged);

   // 

   // label9

   // 

   this.label9.AutoSize = true;

   this.label9.Location = new System.Drawing.Point(4, 83);

   this.label9.Name = "label9";

   this.label9.Size = new System.Drawing.Size(116, 17);

   this.label9.TabIndex = 28;

   this.label9.Text = "选择四级子部门(OU)";

   // 

   // Form1

   // 

   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

   this.ClientSize = new System.Drawing.Size(584, 429);

   this.Controls.Add(this.comboBox5);

   this.Controls.Add(this.label8);

   this.Controls.Add(this.comboBox6);

   this.Controls.Add(this.label9);

   this.Controls.Add(this.comboBox4);

   this.Controls.Add(this.label7);

   this.Controls.Add(this.comboBox3);

   this.Controls.Add(this.label6);

   this.Controls.Add(this.textBox4);

   this.Controls.Add(this.checkBox3);

   this.Controls.Add(this.checkBox2);

   this.Controls.Add(this.checkBox1);

   this.Controls.Add(this.label5);

   this.Controls.Add(this.textBox3);

   this.Controls.Add(this.textBox2);

   this.Controls.Add(this.textBox1);

   this.Controls.Add(this.button1);

   this.Controls.Add(this.label4);

   this.Controls.Add(this.label1);

   this.Controls.Add(this.comboBox2);

   this.Controls.Add(this.label3);

   this.Controls.Add(this.comboBox1);

   this.Controls.Add(this.label2);

   this.Name = "Form1";

   this.Text = "按OU成批修改信息";

   this.Load += new System.EventHandler(this.Form1_Load);

   this.ResumeLayout(false);

 

  }

  #endregion

 

  /// <summary>

  /// 应用程序的主入口点。

  /// </summary>

  [STAThread]

  static void Main() 

  {

   Application.Run(new Form1());

  }

 

  private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)

  {

   //str=listBox1.SelectedItem.ToString();

   str=comboBox1.SelectedItem.ToString();

   DirectoryEntry de1=new DirectoryEntry();

   de1.Path="LDAP://"+str+",DC=test,DC=net";

   try

   {

    comboBox2.Items.Clear();

    comboBox2.Text="";

    comboBox2.Refresh();

    foreach (DirectoryEntry ch1 in de1.Children)

    {

     // textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

     string str1="";

     str1=ch1.SchemaClassName.ToString();

     if (str1=="organizationalUnit")

     {

      comboBox2.Items.Add(ch1.Name.ToString());

     }

    }

 

    de1.Close();

 

    //textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

    // MessageBox.Show("finish!!!");

   }

   catch(Exception ex)

   {

 

    MessageBox.Show(ex.Message);

   }

   finally

   {}

 

  }

 

  private void Form1_Load(object sender, System.EventArgs e)

  {

   //初始化公司选择框

   DirectoryEntry de1=new DirectoryEntry();

   de1.Path="LDAP://DC=test,DC=net";

   try

   {

    foreach (DirectoryEntry ch1 in de1.Children)

    {

     // textBox1.Text=textBox1.Text+ch1.Name+"/r/n";//ch.Properties["adpath"][0].ToString();

     str=ch1.Name.ToString();

     string str1="";

     //str1=str.Substring(0,str.IndexOf("="));

     str1=ch1.SchemaClassName.ToString();

     if (str1=="organizationalUnit")

     {

      //listBox1.Items.Add(ch1.Name.ToString());

      comboBox1.Items.Add(ch1.Name.ToString());

     // comboBox3.Items.Add(ch1.Name.ToString());

     }

    }

 

    de1.Close();

    //textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

    // MessageBox.Show("finish!!!");

   }

   catch(Exception ex)

   {

 

    strErr=ex.Message;

 

   }

   finally

   {}

 

 

 

  }

 

  private void button1_Click(object sender, System.EventArgs e)

  {

   string strADRoot="";

   string strName="";

   if(comboBox1.Text==""||comboBox2.Text=="")

   {

    strErr="请选择合适的OU";

    goto e1;

   }

   if(checkBox1.Checked)

   {

 

    if(textBox1.Text=="")

    {

 

     strErr="请输入新公司名称";

 

     goto e1;

 

    }

 

   }

   if(checkBox2.Checked)

   {

 

    if(textBox2.Text=="")

    {

     strErr="请输入部门名称!";

     goto e1;

    }

   }

   if(checkBox3.Checked)

   {

    if(textBox4.Text=="请输入新领导的姓名全拼(域帐号)")

    {

     strErr="请输入新领导的姓名全拼(域帐号)!";

     goto e1;

 

    }

    // string strNewManager="";

     //搜索

    //检查是否有重复的帐号

    DirectoryEntry su=new DirectoryEntry("LDAP://DC=test,DC=net");

    DirectorySearcher searcher = new DirectorySearcher();

    searcher.SearchRoot=su;

    searcher.PropertiesToLoad.Add("CN");

    searcher.Filter = "(&(objectClass=user)(sAMAccountName="+textBox4.Text.ToString()+"))";

    searcher.SearchScope = SearchScope.Subtree;

    searcher.Sort = new SortOption("sAMAccountName", SortDirection.Ascending);

    SearchResultCollection results = searcher.FindAll();

    DialogResult dlResult;

    string strMess="您确认要将该OU下的用户的领导更改为:"+results[0].Properties["CN"][0].ToString();

    dlResult=MessageBox.Show(this,strMess,"请确认",MessageBoxButtons.YesNo,

     MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 

     MessageBoxOptions.RightAlign);

    if(dlResult == DialogResult.Yes)

    {

     strManager= results[0].Properties["adspath"][0].ToString(); 

     strManager=strManager.Remove(0,7);

    }

    else

    {

     textBox4.Text="请重新输入新领导的姓名全拼(域帐号)!";

     strErr="请重新输入新领导的姓名全拼(域帐号)!";

     goto e1;

    }

   }

   if((!checkBox3.Checked)&&(!checkBox2.Checked)&&(!checkBox1.Checked))

   {

    strErr="请选择要修改的项目!";

    goto e1;

 

   }

   strADRoot="LDAP://"+str+",DC=test,DC=net";

   DirectoryEntry de=new DirectoryEntry();

   de.Path=strADRoot;

   textBox3.Text="";

 

   try

   {

    foreach(DirectoryEntry chm in de.Children)

    {

     string strType="";

     strType=chm.SchemaClassName.ToString();

     if(strType.ToUpper()=="USER")

     {

      strName=chm.Name.ToString(); 

      //如果选中了修改领导的话

      if(checkBox3.Checked)

      {

       if(chm.Properties.Contains("manager"))

       {

        chm.Properties["manager"][0]=strManager;

        chm.CommitChanges();

        textBox3.Text=textBox3.Text+chm.Name .ToString()+"的领导修改成功!/r/n";

 

       }

       else

       {

        chm.Properties["manager"].Add(strManager);

        chm.CommitChanges();

        textBox3.Text=textBox3.Text+chm.Name .ToString()+"的领导添加成功!/r/n";

 

       }

      }

     //修改公司

     if(checkBox1.Checked)

     {

      if(chm.Properties.Contains("company"))

      {

       chm.Properties["company"][0]=textBox1.Text.ToString();

       chm.CommitChanges();

       textBox3.Text=textBox3.Text+chm.Name .ToString()+"的公司名称修改成功!/r/n";

      }

      else

      {

       chm.Properties["company"].Add(textBox1.Text.ToString());

       chm.CommitChanges();

       textBox3.Text=textBox3.Text+chm.Name .ToString()+"的公司名称添加成功!/r/n";

       //textBox3.Text=textBox3.Text+ch1.Name .ToString()+"/r/n";

      }

     }

 

     //修改部门

     if(checkBox2.Checked)

     {

      if(chm.Properties.Contains("department"))

      {

       chm.Properties["department"][0]=textBox2.Text.ToString();

       chm.CommitChanges();

       textBox3.Text=textBox3.Text+chm.Name .ToString()+"的部门名称修改成功!/r/n";

      }

      else

      {

       chm.Properties["department"].Add(textBox2.Text.ToString());

       chm.CommitChanges();

       //textBox3.Text=textBox3.Text+ch1.Name .ToString()+"/r/n";

       textBox3.Text=textBox3.Text+chm.Name .ToString()+"的部门名称添加成功!/r/n";

      }

     }

 

 

 

     }

 

    }

    MessageBox.Show("修改成功!");

   }

   catch(Exception ex)

   {

    strErr=ex.Message;

    goto e1;

   }

 

   e1: if(strErr!="")

    {

     MessageBox.Show(strErr); 

    }

  }

 

  private void comboBox2_SelectedIndexChanged(object sender, System.EventArgs e)

  {

   //str=listBox1.SelectedItem.ToString();

   str=comboBox2.SelectedItem.ToString()+","+comboBox1.SelectedItem.ToString();

   DirectoryEntry de1=new DirectoryEntry();

   de1.Path="LDAP://"+str+",DC=test,DC=net";

   try

   {

    comboBox3.Items.Clear();

    comboBox3.Text="";

    comboBox3.Refresh();

    foreach (DirectoryEntry ch1 in de1.Children)

    {

     // textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

     string str1="";

     str1=ch1.SchemaClassName.ToString();

     if (str1=="organizationalUnit")

     {

      comboBox3.Items.Add(ch1.Name.ToString());

     }

    }

 

    de1.Close();

 

    //textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

    // MessageBox.Show("finish!!!");

   }

   catch(Exception ex)

   {

 

    MessageBox.Show(ex.Message);

   }

  }

 

  private void comboBox3_SelectedIndexChanged(object sender, System.EventArgs e)

  {

   str=comboBox3.SelectedItem.ToString()+","+comboBox2.SelectedItem.ToString()+","+comboBox1.SelectedItem.ToString();

   DirectoryEntry de1=new DirectoryEntry();

   de1.Path="LDAP://"+str+",DC=test,DC=net";

   try

   {

    comboBox4.Items.Clear();

    comboBox4.Text="";

    comboBox4.Refresh();

    foreach (DirectoryEntry ch1 in de1.Children)

    {

     // textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

     string str1="";

     str1=ch1.SchemaClassName.ToString();

     if (str1=="organizationalUnit")

     {

      comboBox4.Items.Add(ch1.Name.ToString());

     }

    }

 

    de1.Close();

 

    //textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

    // MessageBox.Show("finish!!!");

   }

   catch(Exception ex)

   {

 

    MessageBox.Show(ex.Message);

   }

  }

 

  private void comboBox4_SelectedIndexChanged(object sender, System.EventArgs e)

  {

   str=comboBox4.SelectedItem.ToString()+","+comboBox3.SelectedItem.ToString()+","+comboBox2.SelectedItem.ToString()+","+comboBox1.SelectedItem.ToString();

   DirectoryEntry de1=new DirectoryEntry();

   de1.Path="LDAP://"+str+",DC=test,DC=net";

   try

   {

    comboBox6.Items.Clear();

    comboBox6.Text="";

    comboBox6.Refresh();

    foreach (DirectoryEntry ch1 in de1.Children)

    {

     // textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

     string str1="";

     str1=ch1.SchemaClassName.ToString();

     if (str1=="organizationalUnit")

     {

      comboBox6.Items.Add(ch1.Name.ToString());

     }

    }

 

    de1.Close();

 

    //textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

    // MessageBox.Show("finish!!!");

   }

   catch(Exception ex)

   {

 

    MessageBox.Show(ex.Message);

   }

  }

 

  private void comboBox6_SelectedIndexChanged(object sender, System.EventArgs e)

  {

   str=comboBox6.SelectedItem.ToString()+","+comboBox4.SelectedItem.ToString()+","+

    comboBox3.SelectedItem.ToString()+","+comboBox2.SelectedItem.ToString()+","+

    comboBox1.SelectedItem.ToString();

   DirectoryEntry de1=new DirectoryEntry();

   de1.Path="LDAP://"+str+",DC=test,DC=net";

   try

   {

    comboBox5.Items.Clear();

    comboBox5.Text="";

    comboBox5.Refresh();

    foreach (DirectoryEntry ch1 in de1.Children)

    {

     // textBox1.Text=textBox1.Text+str+"/r/n";//ch.Properties["adpath"][0].ToString();

     string str1="";

     str1=ch1.SchemaClassName.ToString();

     if (str1=="organizationalUnit")

     {

      comboBox5.Items.Add(ch1.Name.ToString());

     }

    }

 

    de1.Close();

 

    //textBox1.Text=textBox1.Text+"--------------next------------------------/r/n";

    // MessageBox.Show("finish!!!");

   }

   catch(Exception ex)

   {

 

    MessageBox.Show(ex.Message);

   }

 

  }

 

  private void comboBox5_SelectedIndexChanged(object sender, System.EventArgs e)

  {

   str=comboBox5.SelectedItem.ToString()+","+comboBox6.SelectedItem.ToString()+","+comboBox4.SelectedItem.ToString()+","+

    comboBox3.SelectedItem.ToString()+","+comboBox2.SelectedItem.ToString()+","+

    comboBox1.SelectedItem.ToString();

 

  }

 

 

 

 }

 

}

 

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭