C#中 DirectoryEntry组件应用实例
DirectoryEntry组件
1. 功能
DirectoryEntry类封装Active Directory层次结构中的节点或对象,使用该类可以绑定到对象,或者读取和更新属性。图1所示为DirectoryEntry组件。

图1 DirectoryEntry组件
2.属性
DirectoryEntry组件常用属性及说明如表1所示。

表1 DirectoryEntry组件常用属性及说明
下面对比较重要的属性进行详细介绍。
Path属性:用于获取或设置DirectoryEntry对象的路径,默认值为空字符串(“”)。
语法:
public string Path { get; set; }
属性值:DirectoryEntry对象的路径,默认值为空字符串(“”)。
示例
Path属性的使用
本示例主要是设置Path属性,将本机上的用户名、工作组添加到treeview控件中。其运行结果如图2所示。

图2 Path属性
程序主要代码如下:
完整程序代码如下:
★★★★★主程序文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace _8_26
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmDirectoryEntry());
}
}
}
★★★★★frmDirectoryEntry窗体设计文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.Diagnostics;
namespace _8_26
{
public partial class frmDirectoryEntry : Form
{
public frmDirectoryEntry()
{
InitializeComponent();
}
//以下函数实现路径及属性的添加功能
private void AddPathAndProperties(TreeNode node, DirectoryEntry entry)
{
node.Nodes.Add(new TreeNode("Path:" + entry.Path));
TreeNode propertyNode = new TreeNode("Properties");
node.Nodes.Add(propertyNode);
foreach (string propertyName in entry.Properties.PropertyNames)
{
string oneNode = propertyName + ":" + entry.Properties[propertyName][0].ToString();
propertyNode.Nodes.Add(new TreeNode(oneNode));
}
}
private void frmDirectoryEntry_Load(object sender, EventArgs e)
{
//entryPC.Path = "WinNT://192.168.1.96/ZHY";
entryPC.Path = "WinNT://workgroup/Localhost";//Workgroup计算机所处的组//ZHY计算机名
//entryPC.Path = "LDAP://ZHY/rootDSE";
TreeNode users = new TreeNode("Users");
TreeNode groups = new TreeNode("Groups");
TreeNode services = new TreeNode("Services");
viewPC.Nodes.AddRange(new TreeNode[] { users, groups, services });
foreach (DirectoryEntry child in entryPC.Children)
{
TreeNode newNode = new TreeNode(child.Name);
switch (child.SchemaClassName)
{
case "User":
users.Nodes.Add(newNode);
break;
case "Group":
groups.Nodes.Add(newNode);
break;
case "Service":
services.Nodes.Add(newNode);
break;
}
AddPathAndProperties(newNode, child);
//http://www.isstudy.com
}
}
}//
}
★★★★★frmDirectoryEntry窗体代码文件完整程序代码★★★★★