如何从 LDAP 路径字符串中提取项目

How to Extract Items From an LDAP Path String

是否有 "right" 从以下字符串中检索 CN 的方法:

"LDAP://CN=Firstname Surname,OU=Domain Administrators,DC=DOMAIN1,DC=co,DC=uk"

我从 DirectorySearcher

中检索到的

目前我正在这样做:

var name = result.Path.Split('=')[1].Split(',')[0];

但这并不是最好的方法 - 有没有人知道任何替代方法?

你可以看看这篇文章:An RFC 2253 Compliant Distinguished Name Parser

There are three main classes in this code:

  • DN, which represents a full distinguished name
  • RDN, which represents a relative distinguished name
  • RDNComponent, which represents the individual components of a multivalued RDN

    DN myDN = new DN(@"CN=Pete Everett\, esq.,OU=People,DC=example,DC=com");

To print out a DN object, you use its ToString() method, as you'd expect.

Console.WriteLine(myDN.ToString());
// prints out:
// CN=Pete Everett\, esq.,OU=People,DC=example,DC=com

But if you'd like more control over the formatting, you can specify categories of characters to escape.

Console.WriteLine(myDN.ToString(EscapeChars.None));
// prints out:
// CN=Pete Everett, esq.,OU=People,DC=example,DC=com
// (Note that this is an incorrect DN format, and will not parse correctly.)

To get the parent object of a given DN object, you can use its Parent property.

DN myParentDN = myDN.Parent;
Console.WriteLine(myParentDN.ToString());
// prints out:
// OU=People,DC=example,DC=com

您可以使用模式匹配的强大功能来完成此操作,而不是依赖外部依赖项。

这是一位 regular expression to extract info from ldap distinguishedNames by RegExr.com 用户 Massimo Bonvicini

这里是 C# 中的一个基本示例

using System.Text.RegularExpressions;

string pattern = "^(?:(?<cn>CN=(?<name>[^,]*)),)?(?:(?<path>(?:(?:CN|OU)=[^,]+,?)+),)?(?<domain>(?:DC=[^,]+,?)+)$";
string dn = "CN=Exchange Servers,OU=Microsoft Exchange Security Groups,DC=gr-u,DC=it";

Match match = Regex.Matches(myDN, pattern)[0];

Console.WriteLine(match.Groups("cn").Value);
 // output: 
 // CN=Help Desk

Console.WriteLine(match.Groups("name").Value);
 // output:
 // Help Desk

Console.WriteLine(match.Groups("path").Value);
 // output:
 // OU=Microsoft Exchange Security Groups

Console.WriteLine(match.Groups("domain").Value);
 // output:
 // DC=gr-u,DC=it