首先我想说我是编程新手。我在 Visual Studio 中创建了一个表单,其中包含一个名为 tEmailAddress 的文本框和一个按钮 bExport。当我将我的用户名放在 tEmailAddress 字段中并按下按钮时,我希望它显示一个带有 AD 显示名称字段的消息框。
由于缺乏 C# 知识,我无法获得想要的结果。没有错误,当我单击按钮时,没有任何内容返回到消息框。请指教。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
namespace ReadFromAD
{
public partial class Form1 : Form
{
public static DirectoryEntry GetDirectoryEntry()
{
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://OU=Users,DC=mydomain,DC=com";
de.AuthenticationType = AuthenticationTypes.Secure;
return de;
}
String FindName(String userAccount)
{
DirectoryEntry entry = GetDirectoryEntry();
try
{
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + userAccount + ")";
search.PropertiesToLoad.Add("displayName");
SearchResult result = search.FindOne();
if (result != null)
{
return result.Properties["displayname"][0].ToString();
}
else
{
return "Unknown User";
}
}
catch (Exception ex)
{
string debug = ex.Message;
return "";
}
}
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void bExport_Click(object sender, EventArgs e)
{
if (tEmailAddress.Text != "")
{
string account = tEmailAddress.Text.ToString();
FindName(account);
}
}
}
}