public class DistinguishedName
{
///
/// Represents a name/value pair within a distinguished name, including the index of the part.
///
public struct Part
{
public Part(string name, string value, int index = -1)
: this()
{
Name = name;
Value = value;
Index = index;
}
public string Name { get; private set; }
public string Value { get; private set; }
public int Index { get; private set; }
///
/// Performs a case-insensitive name comparison
///
///
///
public bool IsNamed(string name)
{
return string.Equals(name, this.Name, StringComparison.OrdinalIgnoreCase);
}
}
///
/// Parses the given distinguished name into parts
///
///
///
public static IEnumerable Parse(string dn)
{
int i = 0;
int a = 0;
int v = 0;
int index = -1;
bool inNamePart = true;
bool isQuoted = false;
var namePart = new char[50];
var valuePart = new char[200];
string attrName, attrValue;
while (i < dn.Length)
{
char ch = dn[i++];
if (!inNamePart && ch == '"')
{
isQuoted = !isQuoted;
continue;
}
if (!isQuoted)
{
if (ch == '\\')
{
valuePart[v++] = ch;
valuePart[v++] = dn[i++];
continue;
}
if (ch == '=')
{
inNamePart = false;
isQuoted = false;
continue;
}
if (ch == ',')
{
inNamePart = true;
attrName = new string(namePart, 0, a);
attrValue = new string(valuePart, 0, v);
yield return new Part(attrName, attrValue, ++index);
isQuoted = false;
a = v = 0;
continue;
}
}
if (inNamePart && a == 0 && char.IsWhiteSpace(ch)) // skip whitespace
continue;
else if (inNamePart)
namePart[a++] = ch;
else
valuePart[v++] = ch;
}
attrName = new string(namePart, 0, a);
attrValue = new string(valuePart, 0, v);
yield return new Part(attrName, attrValue, ++index);
}
}