設定AD密碼
using System.DirectoryServices
無法使用生效時,須使用加入參考的方式
1.統一於web.config內設定登入AD的資訊
xxx.aspx中的程式碼:
protected void Button1_Click(object sender, EventArgs e)
{
Label4.Text = "";
string strLogin = TextBox1.Text;
string Opwd = TextBox2.Text;
string Npwd = TextBox3.Text;
DirectoryEntry root = new DirectoryEntry(ConfigurationManager.AppSettings["OU path"], ConfigurationManager.AppSettings["root account"], ConfigurationManager.AppSettings["root password"]);
DirectorySearcher ADSearcher = new DirectorySearcher(root);
ADSearcher.Filter = "(&(objectClass=user)(sAMAccountName=" + strLogin + "))";//strLogin為mail的帳號
SearchResult Result = ADSearcher.FindOne();
DirectoryEntry user = (Result != null) ? Result.GetDirectoryEntry() : null;
if (user == null)
{
Label4.Text = "指定帳戶不存在!!!";
}
else
{
user.Invoke("ChangePassword", new object[] { Opwd, Npwd }); //設密碼用"setPassword" , new object[] { pwd}
user.CommitChanges();
Label4.Text = "密碼變更成功!!!";
}}
web.config內<configuration>輸入:
<configuration>
<appSettings>
<add key="root account" value="test0\administrator"></add>//登入AD server的帳號
<add key="root password" value="Windows2008"></add>//登入AD server的密碼
<add key="OU path" value="LDAP://10.16.16.149/OU=test,DC=com,DC=tw"></add>
</appSettings>
<connectionStrings/>
<system.web>
.....2.直接將登入AD的資訊寫於.aspx.cs中
using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.DirectoryServices;public partial class _Default : System.Web.UI.Page
{
int account_is_exist;
DirectoryEntry de;
protected void Page_Load(object sender, EventArgs e)
{
account_is_exist = 0;
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
de = new DirectoryEntry("LDAP://10.1.42.21/CN=" + TextBox1.Text + ",OU=FEGOA,OU=IT DEPT,OU=Headquarter,DC=HQTEST,DC=feg,DC=com,DC=tw", "Administrator", "oa2008AD");
Label2.Text = de.Name;
account_is_exist = 1;
}
catch
{
account_is_exist = 0;
Label2.Text = "The account is not exist";
}
finally
{
}
if (account_is_exist == 1)
{
//try
//{
de.Invoke("ChangePassword", TextBox2.Text, TextBox3.Text);
Label2.Text = "Change success";
//} 設密碼用"SetPassword"
//catch
//{
Label2.Text = "Change fail";
//}
}
}}