public static string GetEmailTail()
{
string strADPath = "LDAP://dweb1.dep1.com/";
string result = "";
try
{
result = strADPath.Substring(strADPath.ToUpper().LastIndexOf(System.Environment.UserDomainName.ToUpper())).TrimEnd(new char[]
{
'/'
});
}
catch
{
}
return result;
}
public static string GetUserEmail(string account)
{
string result = "";
string emailTail = GetEmailTail();
if (emailTail != "")
{
result = account + "@" + emailTail;
}
return result;
}
public static System.DirectoryServices.DirectoryEntry GetRootDEDefault(string adPath)
{
while (adPath.EndsWith("/"))
{
adPath = adPath.TrimEnd(new char[]
{
'/'
});
}
return new DirectoryEntry(adPath);
}
public static string GetDefaultPassword(string accountID)
{
return accountID + "aA";
}
public static bool IsUserAccountExist(string UserAccount, DirectoryEntry rootDE)
{
bool result = false;
try
{
SearchResult searchResult = new DirectorySearcher(rootDE)
{
Filter = "(&(objectClass=user)(sAMAccountName=" + UserAccount + "))",
SearchScope = SearchScope.Subtree
}.FindOne();
if (searchResult != null)
{
result = true;
}
}
catch
{
}
return result;
}
public static bool CreateNewUserDefault(string sUserName, string sUserDispName, string adPath, string OUstring)
{
bool result = false;
DirectoryEntry rootDEDefault = GetRootDEDefault(adPath);
if (IsUserAccountExist(sUserName, rootDEDefault))
{
return true;
}
string value = sUserName + "@" +GetEmailTail();
string name = "CN=" + sUserName + "," + OUstring;
try
{
DirectoryEntry directoryEntry = rootDEDefault.Children.Add(name, "user");
directoryEntry.Properties["userPrincipalName"].Add(value);
directoryEntry.Properties["samAccountName"].Add(sUserName);
directoryEntry.Properties["description"].Add(sUserDispName);
directoryEntry.Properties["displayname"].Value = sUserDispName;
directoryEntry.Properties["givenName"].Value = sUserDispName;
directoryEntry.Properties["mail"].Value = value;
directoryEntry.CommitChanges();
directoryEntry.Invoke("ChangePassword", new object[]
{
"",
GetDefaultPassword(sUserName)//密码
});
directoryEntry.Properties["userAccountControl"].Value = 512;
//这些值是某些对象的默认 UserAccountControl 值:
//典型用户:0x200 (512)
//域控制器:0x82000 (532480)
//工作站/服务器:0x1000 (4096)
directoryEntry.CommitChanges();
result = true;
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
ADHelper.WriteEvent(string.Concat(new string[]
{
"添加AD用户错误:",
ex.Message,
"\n详细:\n账号:",
sUserName,
ex.InnerException.Message
}), EventLogEntryType.Error);
}
else
{
ADHelper.WriteEvent("添加AD用户错误:" + ex.Message + "\n详细:\n账号:" + sUserName, EventLogEntryType.Error);
}
}
return result;
}
protected void Page_Load(object sender, EventArgs e)
{
SPSecurity.RunWithElevatedPrivileges(delegate() {
CreateNewUserDefault("xiaohongmao3","小红帽3", "LDAP://dweb1.dep1.com/", "OU=it1,OU=it");
});
}