从Active Directory返回值
本文关键字:返回值 Directory Active | 更新日期: 2023-09-27 18:26:23
首先我想说我是编程新手。我在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);
}
}
}
}
FindName
返回一个字符串,但您永远不会在任何地方使用它
string result = FindName(account);
然后,您可以根据需要在bExport_Click
方法中使用局部变量result
更改bExport_Click
以显示消息
private void bExport_Click(object sender, EventArgs e)
{
if (tEmailAddress.Text != "")
{
string account = tEmailAddress.Text.ToString();
MessageBox.Show(FindName(account));
}
}