使用.net操作AD域的一些代码共享

using System.DirectoryServices;


--先应用


 


--添加用户


DirectoryEntry entry = new DirectoryEntry(BaseFunctions.DomainSrv,HttpContext.Current.Session["username"].ToString(),HttpContext.Current.Session["password"].ToString(), AuthenticationTypes.Secure);
   DirectoryEntry  subEntry  =  entry.Children.Find(ou.Value);
   DirectoryEntry deUser = subEntry.Children.Add("cn=" +firstname.Text.ToString()+lastname.Text.ToString(), "user");
   deUser.Properties["userPrincipalName"].Add((accountname.Text.ToString()+"@"+BaseFunctions.Domainname));
   deUser.Properties["samAccountName"].Add(accountname.Text.ToString());//帐户
   deUser.Properties["description"].Value = desc.Text.ToString();
   deUser.Properties["sn"].Add(firstname.Text.ToString());
   deUser.Properties["givenName"].Add(lastname.Text.ToString());
   deUser.Properties["displayName"].Add(firstname.Text.ToString()+lastname.Text.ToString());
    deUser.CommitChanges();


   deUser.Invoke("ChangePassword",new object[]{"",password.Text.ToString()});
   deUser.Properties["userAccountControl"].Value = 0x200;
   deUser.CommitChanges();
   deUser.Close();
   lblShowInfo.Text="添加成功";


 


----修改密码


if(tb_newpass.Value.Trim()!=tb_newpass1.Value.Trim())
   {
    lblShowInfo.Text="两次输入的新密码不一样";
    return;
   }
   try
   {
    DirectoryEntry de=new DirectoryEntry(BaseFunctions.DomainSrv,BaseFunctions.GetUserNameFromSession(),BaseFunctions.GetPassWord());
    
    DirectorySearcher deSearch = new DirectorySearcher(de);
    deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName="+Request.QueryString["username"]+"))";
    deSearch.SearchScope = SearchScope.Subtree;
    SearchResult result = deSearch.FindOne();
    DirectoryEntry de1=result.GetDirectoryEntry();
    object retResult=de1.Invoke("SetPassword", new Object[]{tb_newpass.Value.Trim()});
    lblShowInfo.Text="成功修改密码!";
    de1.Close();
    de.Close();
    de1.Dispose();
    de.Dispose();
   }
   catch(Exception ex)
   {
    if(ex.InnerException!=null)
     lblShowInfo.Text=ex.InnerException.Message;
    else
     lblShowInfo.Text+=ex.Message;
   }


 


---将用户改变组织单位


 


DirectoryEntry de=new DirectoryEntry(BaseFunctions.DomainSrv,HttpContext.Current.Session["username"].ToString(),HttpContext.Current.Session["password"].ToString());
   object o = de.NativeObject;
   DirectorySearcher ds = new DirectorySearcher(de);
   ds.Filter = "(SAMAccountName=" + Server.UrlDecode(Request.QueryString["username"]) + ")";
   ds.PropertiesToLoad.Add("cn");
   SearchResult sr = ds.FindOne();//查找该用户
   
   //Response.Write(sr.GetDirectoryEntry().Properties["name"][0]);


   DirectoryEntry de2=sr.GetDirectoryEntry();//设置de2为用户
   DirectoryEntry  ou2  =  de.Children.Find(Request.QueryString["ou"]);//获取新ou对象
   
   de2.MoveTo(ou2);//移动OU
   de2.CommitChanges();//提交
   Response.Write("<script language=javascript>"); 
   Response.Write("alert('移动完毕');");
   Response.Write("opener.window.location.reload(true);");
   Response.Write("window.close();");
   Response.Write("</script>");


 


--用递归方式显示组织单位.还有小部分没做好,只是显示出来,没优化,有兴趣的同志可以改界面呈现方式


调用函数


GetOu("泉州移动",5);----5代表是显示5级 


 


public void GetOu(string ouname,int amstr)
  {
   DirectoryEntry entry=new DirectoryEntry(BaseFunctions.DomainSrv,BaseFunctions.GetUserNameFromSession(),BaseFunctions.GetPassWord());
   System.DirectoryServices.DirectoryEntry subentry=entry.Children.Find(ouname,"organizationalUnit");


   string ax;
   ax="";
   string am;
   am="";
   foreach(DirectoryEntry res in subentry.Children)
   {
     
    am="";
    foreach(DirectoryEntry res1 in res.Children)
    {
     if(res1.Name.Substring(0,3)=="OU=")
     {
      am=am+"1";
     }


    }


    if(res.Name.Substring(0,3)=="OU=")//判断是组织单位还是其他类型,例如cn=用户,GROUP=组等
    {



     ax=ax+"1"; 
 
     string []strArray;//用于存储上级目录的字符串
     string ou;
     ou="";
     strArray=ouname.Split(',');//分割


     for(int j=strArray.Length;j>0;j--)
     {
      if(j==1)
      {
       if(amstr==ax.Length)
        {
         HttpContext.Current.Response.Write("<img src=images/tree2.gif>");
        }
        else
        {
        HttpContext.Current.Response.Write("<img src=images/tree1.gif>");
       }
      }
      else
      {
       HttpContext.Current.Response.Write("<img src=images/tree3.gif>");
      }


     }//根据上级目录的深度来显示目录树的层次
     
     if(am=="")
     {
      Response.Write("<img src=images/tree6.gif>");
     }
     else
     {
      Response.Write("<img src=images/tree5.gif>");
     }
   
     string []strArray2;
     string tem;
     tem=res.Name.ToString()+","+ouname;//存储本级目录
     strArray2=tem.Split(',');
     for(int k=strArray2.Length;k>0;k--)
     {


      ou=ou+strArray2[k-1].Replace("OU=","/");
     }
     //OU存储本级目录的新格式,例如.泉州移动--网络部--IT中心等


 


     if(HttpContext.Current.Request.QueryString["action"]=="move")
     {
      HttpContext.Current.Response.Write("<a onclick=movechk('"+Server.UrlEncode(res.Name.ToString()+","+ouname)+"','"+HttpContext.Current.Request.QueryString["username"]+"');>"+res.Name.ToString().Replace("OU=","")+"</a><br>");
     }
     else if(HttpContext.Current.Request.QueryString["action"]=="add")
     {
      HttpContext.Current.Response.Write("<a onclick=chk('"+ou+"','"+res.Name.ToString()+","+ouname+"');>"+res.Name.ToString().Replace("OU=","")+"</a><br>");
     
     }
     else
     {
      HttpContext.Current.Response.Write("<a onclick=magchk('"+Server.UrlEncode(res.Name.ToString()+","+ouname)+"');>"+res.Name.ToString().Replace("OU=","")+"</a><br>");
     
     }


     GetOu(res.Name.ToString()+","+ouname,am.Length);
    }
    else
    {
     
    }
   }


 


----显示所有域用户的信息


 


DirectoryEntry de = new DirectoryEntry(BaseFunctions.DomainSrv,HttpContext.Current.Session["username"].ToString(),HttpContext.Current.Session["password"].ToString());
   DirectorySearcher srch=new DirectorySearcher();
   srch.Filter =("(objectclass=User)");


   srch.SearchRoot=de;
   srch.SearchScope = SearchScope.Subtree;
   srch.PropertiesToLoad.Add("sn");
   srch.PropertiesToLoad.Add("givenName");
   srch.PropertiesToLoad.Add("uid");
   srch.PropertiesToLoad.Add("telephoneNumber");
   srch.PropertiesToLoad.Add("employeeNumber");
 
   Response.Write("<table width=100% border=0 align=center Class=border");
   Response.Write("<tr background=images/topbar_bg.gif>");
   Response.Write("<td align=center height=22>帐号</td>");
   Response.Write("<td align=center height=22>名字</td>");
   Response.Write("<td align=center height=22>姓</td>");
   Response.Write("<td align=center height=22>名</td>");
   Response.Write("<td align=center height=22>显示名称</td>");
   Response.Write("<td align=center height=22>手机</td>");
   Response.Write("<td align=center height=22>部门</td>");
   Response.Write("<td align=center height=22>状态</td>");
  
   Response.Write("</tr>");


   foreach(SearchResult res in srch.FindAll())
   {
    if(res.Path.IndexOf("泉州移动")>0)
    {


     Response.Write("<tr class=tdbg>");
     Response.Write("<td align=center>"+res.GetDirectoryEntry().Properties["sAMAccountName"][0]+"</td>");
     Response.Write("<td align=center>"+res.GetDirectoryEntry().Properties["Name"][0]+"</td>");
     Response.Write("<td align=center>"+res.GetDirectoryEntry().Properties["Sn"][0]+"</td>");


     try
     {
      Response.Write("<td align=center>"+res.GetDirectoryEntry().Properties["givenName"][0]+"</td>");
     }
     catch
     {
    
      Response.Write("<td align=center></td>");
    
     }
     
     Response.Write("<td align=center>"+res.GetDirectoryEntry().Properties["displayName"][0]+"</td>");
     try
     {
      Response.Write("<td align=center>"+res.GetDirectoryEntry().Properties["telephoneNumber"][0]+"</td>");
     }
     catch
     {
    
      Response.Write("<td align=center></td>");
    
     }
     try
     {
      Response.Write("<td align=center>"+res.GetDirectoryEntry().Properties["mail"][0]+"</td>");
     }
     catch
     {
    
      Response.Write("<td align=center></td>");
    
     }
     string []strArray;
     string str;
     str="";
     strArray=res.Path.Split(',');
     for(int j=strArray.Length;j>0;j--)


     {
      if(strArray[j-1].Substring(0,3)=="OU=")
      {
       str=str+"-"+strArray[j-1].Replace("OU=","");
      }


     }
     Response.Write("<td align=center>"+str+"</td>");


     if(res.GetDirectoryEntry().Properties["userAccountControl"][0].ToString()=="514")
     {
      Response.Write("<td align=center>锁定</td>"); 
     }
     else
     {
      Response.Write("<td align=center>正常</td>");
    
     }
     /*
     Response.Write("<td align=center>");
     if(res.GetDirectoryEntry().Properties["userAccountControl"][0].ToString()=="514")
     {
      Response.Write("<input type=button value=解锁 onclick=\"javascript:window.open('setstate.aspx?action=1&username="+res.GetDirectoryEntry().Properties["sAMAccountName"][0]+"', 'poppage', 'toolbars=1, scrollbars=0, location=0, statusbars=1, menubars=0, resizable=1, width=50, height=50');\">"); 
     }
     else
     {
      Response.Write("<input type=button value=锁定 onclick=\"javascript:window.open('setstate.aspx?action=2&username="+res.GetDirectoryEntry().Properties["sAMAccountName"][0]+"', 'poppage', 'toolbars=1, scrollbars=0, location=0, statusbars=1, menubars=0, resizable=1, width=50, height=50');\">");
     }
     Response.Write("<input type=button value=移动部门 onclick=\"javascript:window.open('ou.aspx?action=move&username="+res.GetDirectoryEntry().Properties["sAMAccountName"][0]+"', 'poppage', 'toolbars=1, scrollbars=1, location=0, statusbars=1, menubars=0, resizable=1, width=200, height=650');\">");
     Response.Write("<input type=button value=更改密码 onclick=\"javascript:window.open('changeuserpass.aspx?action=password&username="+res.GetDirectoryEntry().Properties["sAMAccountName"][0]+"', 'poppage', 'toolbars=1, scrollbars=1, location=0, statusbars=1, menubars=0, resizable=1, width=500, height=150');\">");
   
     Response.Write("</td>");
     */
     Response.Write("</tr>");
     //CreateExcelFile2(res.GetDirectoryEntry().Password.ToString(),res.GetDirectoryEntry().Properties["Name"][0].ToString(),res.GetDirectoryEntry().Properties["telephoneNumber"][0].ToString(),res.GetDirectoryEntry().Properties["sn"][0].ToString(),res.GetDirectoryEntry().Properties["givenName"][0].ToString(),res.GetDirectoryEntry().Properties["displayName"][0].ToString());
    }
   }
   Response.Write("</table>");


posted @ 2009-01-22 10:00  雷君  阅读(921)  评论(0编辑  收藏  举报