我正在尝试从存储用户信息的SQL Server表中执行SELECT *
,然后将这些条目与Active Directory数据库进行比较。
如果我指定一个特定的人,它会起作用,但当我尝试将搜索结果整理到数据表中时,它会出错。 Code
和Description
是同一个。
在数据库中,代码是AD的描述字段中的代码。那么应该发生的是,它将数据库中的所有数据提取到DataTable
,对于DataTable
我搜索AD中的每个结果,并在AD的电子邮件字段中返回电子邮件地址。同样,当我输入特定的名字和姓氏时它会起作用,但是当我使用下面的代码时,我只是得到一个未处理的异常错误。
这是代码。谢谢!
private void btnRun_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string APIdbUser = "dbuser";
string APIdbServer = "dbserver";
string APIdbUserPW = "dbpassword";
string APIdbDatabase = "thedatabase";
string TrustedConnection = "no";
var ConnectionTimeout = "30";
using (SqlConnection myConnection = new SqlConnection("user id=" + APIdbUser + ";" +
"password=" + APIdbUserPW + ";server=" + APIdbServer + ";" +
"Trusted_Connection=" + TrustedConnection + ";" +
"database=" + APIdbDatabase + "; " +
"connection timeout=" + ConnectionTimeout))
{
using (var myCommand = new SqlCommand("SELECT * FROM dbo.Users WHERE FirstName!='NULL' AND LastName!='NULL' AND Gender!='NULL';", myConnection))
{
myConnection.Open();
using (SqlDataReader dr = myCommand.ExecuteReader())
{
dt.Load(dr);
}
myConnection.Close();
}
}
foreach (DataRow dr in dt.Rows)
{
string ldapAddress = "LDAP://url";
string ldapusername = "ldapuser";
string ldappassword = "ldapuser";
DirectoryEntry de = new DirectoryEntry(ldapAddress, ldapusername, ldappassword);
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&((&(objectCategory=person)(objectClass=user)))(givenName=" + dr.Field<string>("FirstName") + ")(sn=" + dr.Field<string>("LastName") + ")(description=" + dr.Field<string>("Code") + "))";
ds.SearchScope = SearchScope.Subtree;
SearchResult rs = ds.FindOne();
if (dr.Field<string>("Code") == rs.GetDirectoryEntry().Properties["description"].Value.ToString())
{
MessageBox.Show("This users email address is: " + rs.GetDirectoryEntry().Properties["mail"].Value.ToString());
}
//MessageBox.Show(dr.Field<string>("FirstName") + " " + dr.Field<string>("LastName"));
}
}
以下是我修复它的方法
if (rs != null)
{
if (dr.Field<string>("Code") == rs.GetDirectoryEntry().Properties["description"].Value.ToString())
{
if (rs.GetDirectoryEntry().Properties["mail"].Value == null)
{
MessageBox.Show("This email is N/A.");
}
else
{
MessageBox.Show("This users email address is: " + rs.GetDirectoryEntry().Properties["mail"].Value.ToString());
}
}
}
答案 0 :(得分:0)
必须检查IF NOT null
if (rs != null)
{
if (dr.Field<string>("Code") == rs.GetDirectoryEntry().Properties["description"].Value.ToString())
{
if (rs.GetDirectoryEntry().Properties["mail"].Value == null)
{
MessageBox.Show("This email is N/A.");
}
else
{
MessageBox.Show("This users email address is: " + rs.GetDirectoryEntry().Properties["mail"].Value.ToString());
}
}
}