directoryentry

C#中directoryentry怎么使用

小亿
151
2023-07-11 12:14:51
栏目: 编程语言

在C#中,DirectoryEntry类用于表示目录服务中的目录项。你可以使用DirectoryEntry类来创建、删除、修改和搜索目录项。以下是一些常见的DirectoryEntry的用法示例:

  1. 创建一个新的目录项:
DirectoryEntry entry = new DirectoryEntry("LDAP://cn=John Doe,ou=Users,dc=example,dc=com");
entry.Properties["givenName"].Value = "John";
entry.Properties["sn"].Value = "Doe";
entry.Properties["userPrincipalName"].Value = "john.doe@example.com";
entry.CommitChanges();
  1. 获取目录项的属性值:
DirectoryEntry entry = new DirectoryEntry("LDAP://cn=John Doe,ou=Users,dc=example,dc=com");
string firstName = entry.Properties["givenName"].Value.ToString();
string lastName = entry.Properties["sn"].Value.ToString();
string email = entry.Properties["userPrincipalName"].Value.ToString();
  1. 修改目录项的属性值:
DirectoryEntry entry = new DirectoryEntry("LDAP://cn=John Doe,ou=Users,dc=example,dc=com");
entry.Properties["givenName"].Value = "John";
entry.Properties["sn"].Value = "Smith";
entry.CommitChanges();
  1. 删除目录项:
DirectoryEntry entry = new DirectoryEntry("LDAP://cn=John Doe,ou=Users,dc=example,dc=com");
entry.DeleteTree();
  1. 搜索目录项:
DirectoryEntry root = new DirectoryEntry("LDAP://dc=example,dc=com");
DirectorySearcher searcher = new DirectorySearcher(root);
searcher.Filter = "(objectClass=user)";
searcher.PropertiesToLoad.Add("cn");
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("sn");
SearchResultCollection results = searcher.FindAll();
foreach (SearchResult result in results)
{
DirectoryEntry entry = result.GetDirectoryEntry();
string firstName = entry.Properties["givenName"].Value.ToString();
string lastName = entry.Properties["sn"].Value.ToString();
Console.WriteLine("Name: " + firstName + " " + lastName);
}

这些示例只是DirectoryEntry类的一些基本用法,你可以根据自己的需求进一步探索该类的功能。

0
看了该问题的人还看了