Question

Hi I am looking for a simple way to et just the name after the CN value

CN=Andrew Adams,OU=Services,OU=Users,OU=GIE,OU=CSP,OU=STAFF,DC=example,DC=net

is there an easy way to do this? I am currently doing this:

ResultPropertyValueCollection manager = result.Properties["manager"];
string managerUserName = manager[0].ToString();

string[] managerNameParts = managerUserName.Split(',');

string managerName = managerNameParts[0].Substring(4);

Console.WriteLine("Manager Name:" + managerName);

but it feels kind of bad.

Was it helpful?

Solution

This is a great place to use Regular Expressions. Try this:

var text = "CN=Andrew Adams,OU=Services,OU=Users,OU=GIE,OU=CSP,OU=STAFF,DC=example,DC=net";
var match = Regex.Match(text, @"CN=([^,]+)");
if (match.Success) return match.Groups[0].Value;

The expression CN=([^,]+) will look for the text CN= followed by one or more non-commas, and will stick that part of it into Groups[0].

OTHER TIPS

You can do this:

var name = "CN=Andrew Adams,OU=Services,OU=Users,OU=GIE,OU=CSP,OU=STAFF,DC=example,DC=net"
.Split(',')[0].Split('=')[1];

Demo

What it does is splits on , and takes the first element and then splits it by = and takes the second element.

If you cannot have the same format, you can do a regex:

Regex.Match(name,@"(?<=CN=)[^,]+").Value;

Another option, using LINQ.

If the name/value pair exists anywhere in the string, you'll get it; if not, managerName will be null.

var managerName = input.Split(',')
                       .Where(x => x.StartsWith("CN="))
                       .Select(x => x.Split('=')[1])
                       .SingleOrDefault();

I find doing it like this fairly easy to read:

var input = @"CN=Andrew Adams,OU=Services,OU=Users,OU=GIE,OU=CSP,OU=STAFF,DC=example,DC=net";

var items = input.Split(',');

var keyValues = items.Select(x =>
                {
                    var split = x.Split('=');
                    return new { Key = split[0], Value = split[1] };
                });

var managerName = keyValues.Single(x => x.Key == "CN").Value;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top