如何从LDAP路径字符串中提取项目
本文关键字:提取 项目 字符串 路径 LDAP | 更新日期: 2024-09-19 19:16:03
是否有"正确"的方法从以下字符串中检索CN:
"LDAP://CN=Firstname Surname,OU=Domain Administrators,DC=DOMAIN1,DC=co,DC=uk"
我从DirectorySearcher
中检索到的
目前我正在做这个:
var name = result.Path.Split('=')[1].Split(',')[0];
但这并不是最好的方法——有人知道有其他选择吗?
你可以看看这篇文章:一个符合RFC 2253的可分辨名称解析器
此代码中有三个主要类:
- DN,表示可分辨的全名
- RDN,表示相对可分辨的名称
RDNComponent,表示多值RDN 的单个组件
DN myDN = new DN(@"CN=Pete Everett', esq.,OU=People,DC=example,DC=com");
要打印出DN对象,可以使用它的ToString()方法预料
Console.WriteLine(myDN.ToString()); // prints out: // CN=Pete Everett', esq.,OU=People,DC=example,DC=com
但是,如果您希望对格式进行更多控制,可以指定要转义的字符类别。
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.)
要获取给定DN对象的父对象,可以使用其parent所有物
DN myParentDN = myDN.Parent; Console.WriteLine(myParentDN.ToString()); // prints out: // OU=People,DC=example,DC=com
您可以使用模式匹配的功能来实现这一点,而不是依赖于外部依赖。
以下是RegExr.com用户Massimo Bonvicini从ldap distinguishedNames中提取信息的正则表达式
下面是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