65.9K
CodeProject 正在变化。 阅读更多。
Home

通过 C# (Visual Studio) 访问 Active Directory 对象

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2011年1月27日

CPOL
viewsIcon

64174

通过 C# (Visual Studio) 访问 Active Directory 对象

背景本文旨在帮助初学者学习如何通过 C# 代码访问 Active Directory 对象。Using the Code要使用此代码,您需要一台安装了 Active Directory 的 Windows 服务器以及您机器上的 Visual Studio。系统引用请确保在您的代码中包含以下命名空间
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
目录条目对象现在我们为我们的 Active Directory 创建一个目录条目对象。
DirectoryEntry dir = new DirectoryEntry("LDAP://your_domain_name");
创建搜索对象并执行搜索DirectorySearcher 对象搜索 Active Directory。您可以设置 filter 属性以检索特定的记录。我还在使用 AND "&" 属性来组合两个条件。
DirectorySearcher search = new DirectorySearcher(dir);

search.Filter = "(&(objectClass=user)(givenname=First_Name))";
处理搜索结果首先,我们创建一个 SearchResult 对象来获取搜索数据。 接下来,我展示了如何获取该对象的所有属性名称,稍后可以用来获取任何特定的属性值。 最后,我们从搜索结果中获取目录条目,然后指定特定的属性名称以获取其值。
SearchResult searchresult = search.FindOne(); // You can also use the FindAll() method for multiple objects.

   if (searchresult != null)
   {
	foreach(System.Collections.DictionaryEntry direntry in searchresult.Properties) 
                    TextBox1.Text += direntry.Key.ToString() +"\n"; // This will give you all the property names that are set for that particular object,which you can use to get a specific value.I have used a Multiline textbox here.			      

        TextBox1.Text += searchresult.GetDirectoryEntry().Properties["sn"].Value.ToString(); // I am displaying the lastname/surname in simple textbox.
   }
关注点我希望这篇文章能帮助初学者了解如何通过 C# 代码访问 Active Directory 对象。
© . All rights reserved.