Is there a .NET class that can parse CN= strings out of LDAP?

后端 未结 7 579
梦毁少年i
梦毁少年i 2020-12-17 18:15

I\'ve got a string that I\'m fetching from LDAP for Active Directory group membership and I need to parse it to check if the user is a member of the AD group. Is there a cl

7条回答
  •  轮回少年
    2020-12-17 18:59

    To parse the DistinquishedName you have to pay attention to the escape characters. Here's a method that will parse the string correctly and return a list of key value pairs.

        public static List> ParseDistinguishedName(string input)
        {
            int i = 0;
            int a = 0;
            int v = 0;
            var attribute = new char[50];
            var value = new char[200];
            var inAttribute = true;
            string attributeString, valueString;
            var names = new List>();
    
            while (i < input.Length)
            {
                char ch = input[i++];
                switch(ch)
                {
                    case '\\':
                        value[v++] = ch;
                        value[v++] = input[i++];
                        break;
                    case '=':
                        inAttribute = false;
                        break;
                    case ',':
                        inAttribute = true;
                        attributeString = new string(attribute).Substring(0, a);
                        valueString = new string(value).Substring(0, v);
                        names.Add(new KeyValuePair(attributeString, valueString));
                        a = v = 0;
                        break;
                    default:
                        if (inAttribute)
                        {
                            attribute[a++] = ch;
                        }
                        else
                        {
                            value[v++] = ch;
                        }
                        break;
                }
            }
    
            attributeString = new string(attribute).Substring(0, a);
            valueString = new string(value).Substring(0, v);
            names.Add(new KeyValuePair(attributeString, valueString));
            return names;
        }
    
        static void Main(string[] args)
        {
            const string TestString = "CN=BY2STRAKRJOB2,OU=MSNStorage,OU=RESOURCE,OU=PRODUCTION,DC=phx,DC=gbl,STREET=street address,L=locality Name,C=Country Name,UID=user id,STUFF=\\,\\.\\+\"<>;\\=\\0A";
    
            var names = ParseDistinguishedName(TestString);
            foreach (var pair in names)
            {
                Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
            }
        }
    

提交回复
热议问题