c# - 如何使用 C# 使用 DomainName 获取 AD 中的 OU 名称列表?

标签 c# active-directory

我想从 Active Directory 中获取 OU 列表。

我只有域名。

我如何使用 C# 实现此目的?

最佳答案

尝试这样的事情:

// connect to "RootDSE" to find default naming context
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");

string defaultContext = rootDSE.Properties["defaultNamingContext"][0].ToString();

// bind to default naming context - if you *know* where you want to bind to - 
// you can just use that information right away
DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + defaultContext);

// set up directory searcher based on default naming context entry
DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);

// SearchScope: OneLevel = only immediate subordinates (top-level OUs); 
// subtree = all OU's in the whole domain (can take **LONG** time!)
ouSearcher.SearchScope = SearchScope.OneLevel;
// ouSearcher.SearchScope = SearchScope.Subtree;

// define properties to load - here I just get the "OU" attribute, the name of the OU
ouSearcher.PropertiesToLoad.Add("ou");

// define filter - only select organizational units
ouSearcher.Filter = "(objectCategory=organizationalUnit)";

// do search and iterate over results
foreach (SearchResult deResult in ouSearcher.FindAll())
{
    string ouName = deResult.Properties["ou"][0].ToString();
}

如果您有域名(例如 mycompany.com),那么 LDAP 根域通常将被称为dc=mycompany,dc=com - 这是一个约定,但不一定非得那样。这就是为什么我要连接到 LDAP://RootDSE 虚拟 LDAP 根目录并读取属性 Default Naming Context,它会给我默认的 LDAP 路径。

如果您知道您想要连接到哪里 - 请随意跳过第一步,只需提供有效的 LDAP 路径(例如 LDAP://dc=YourCompany,dc=co ,dc=jp 或其他)来创建 domainRoot 目录条目。

关于c# - 如何使用 C# 使用 DomainName 获取 AD 中的 OU 名称列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13605618/

相关文章:

ruby-on-rails - 通过 Ruby 或 Rails 的 LDAP

c# - 在数字中查找特定数字

c# - 如何在 C# 中创建包含“

c# - .NET MAUI 将列表绑定(bind)到上下文 View

php - 从浏览器获取用户身份

azure - ADAL:在哪里可以查看资源 ID?

c# - 查询事件目录以直接获取专有名称的电子邮件属性?

c# - 在 IEnumerable 上使用 Observable 集合的优缺点

c# - 将数据从一个 Controller 操作传递到 ASP.Net MVC 5 中的另一个 Controller 操作

java - digest-uri 与为此服务器注册的任何 LDAP SPN 都不匹配