溫馨提示×

C#中DirectoryEntry對象怎么使用

c#
小億
170
2023-09-14 22:00:35
欄目: 編程語言

DirectoryEntry對象在C#中用于操作和管理目錄服務(也稱為Active Directory)中的目錄項。下面是一些常用的DirectoryEntry對象的使用方法:

  1. 創(chuàng)建一個DirectoryEntry對象:
DirectoryEntry entry = new DirectoryEntry("LDAP://servername/ou=users,dc=example,dc=com", "admin", "password");
  1. 獲取目錄項的屬性:
string username = entry.Properties["sAMAccountName"].Value.ToString();
string email = entry.Properties["mail"].Value.ToString();
  1. 修改目錄項的屬性:
entry.Properties["displayName"].Value = "John Doe";
entry.CommitChanges();
  1. 添加新的目錄項:
DirectoryEntry newUser = entry.Children.Add("CN=New User", "user");
newUser.Properties["sAMAccountName"].Value = "newuser";
newUser.Properties["givenName"].Value = "New";
newUser.Properties["sn"].Value = "User";
newUser.Properties["userPrincipalName"].Value = "newuser@example.com";
newUser.CommitChanges();
  1. 刪除目錄項:
entry.Children.Remove("CN=New User");
  1. 枚舉子目錄項:
foreach (DirectoryEntry child in entry.Children)
{
Console.WriteLine(child.Name);
}

以上是一些常用的DirectoryEntry對象的使用示例。請注意,使用DirectoryEntry對象操作Active Directory時需要相應的權限。

0