我不熟悉使用Active Directory并希望创建从用户获取用户名的搜索表单,使用该名称进行通配符搜索并返回找到的用户名及其计算机名称。我使用以下代码:
private SearchResultCollection GetSearchResultCollection(string DomainName, string Filter)
{
try
{
/* Getting connection info. */
Login ObjLogin = new Login();
string ServerIP = ObjLogin.GetSystemSettingByName("LDAPServer");
string Port = ObjLogin.GetSystemSettingByName("Port");
string UserName = ObjLogin.GetSystemSettingByName("ADUsername");
string Password = ObjLogin.GetSystemSettingByName("ADPassword");
DirectoryEntry Ldap = new DirectoryEntry(@"LDAP://" + ServerIP + ":" + Port, UserName, Password);
DirectorySearcher LdapSearcher = new DirectorySearcher(Ldap);
LdapSearcher.Filter = Filter;
return LdapSearcher.FindAll();
}
catch (Exception ex)
{
return null;
}
}
public string FindUsernameInAD(string Username, out int Count)
{
Count = 0;
string FoundUsername = Username;
try
{
/* Getting domain name */
Login ObjLogin = new Login();
string DomainName = ObjLogin.GetSystemSettingByName("DomainName");
SearchResultCollection LdapSearcherResults = GetSearchResultCollection(DomainName, "(&(objectClass=user))");
foreach (SearchResult resultLdap in LdapSearcherResults)
{
if ((resultLdap.Properties["sAMAccountName"] != null) && (resultLdap.Properties["sAMAccountName"].Count > 0))
{
if (resultLdap.Properties["sAMAccountName"][0].ToString().ToLower().Contains(Username.ToLower()))
{
//return resultLdap.Properties["cn"][0].ToString() + "(" + resultLdap.Properties["sAMAccountName"][0].ToString() + "@" + Username + ")";
FoundUsername = resultLdap.Properties["sAMAccountName"][0].ToString();
Count++;
}
}
}
}
catch (Exception ex)
{
/* Catch Exception Here */
log.Error("Error in UserManager.cs, FindUsernameInAD function: " + ex.Message);
}
return FoundUsername;
}
此代码返回我的用户名但没有计算机名称,那么如何获取计算机名称?另外我想知道"用户的计算机名称对于活动目录中的每个用户是唯一的吗?"