ADHelper中AD属性赋值的修正

最近在做AD编程方面的东西,参考了网上流传的ADHelper,貌似AD的属性赋值的方法都是有误的。
原方法类似下面这样:

 1 public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
 2          {
 3               if(propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
 4               {
 5                    if(de.Properties.Contains(propertyName))
 6                    {
 7                        de.Properties[propertyName][0= propertyValue; 
 8                    }
 9                    else
10                    {
11                        de.Properties[propertyName].Add(propertyValue);
12                    }
13               }
14          }

但是在实际的操作中您会发现,有时候我们已经赋值过的属性需要改成空值,那用这个方法是怎么样也不会生效了。而且您也会发现,把propertyValue的空值判断去掉,也不会通过的,因为,不管存在不存在这个属性,你将这个属性直接赋值为空就会报错的。
要将属性值赋值为空值,是用移除的方法来实现的,下面的方法是经过更正的:
 1 public static void SetProperty(DirectoryEntry entry, string propertyName, string propertyValue)
 2         {
 3             if (entry.Properties.Contains(propertyName))
 4             {
 5                 if (string.IsNullOrEmpty(propertyValue))
 6                 {
 7                     object o = entry.Properties[propertyName].Value;
 8                     entry.Properties[propertyName].Remove(o);
 9                 }
10                 else
11                 {
12                     entry.Properties[propertyName][0= propertyValue;
13                 }
14             }
15             else
16             {
17                 if (!string.IsNullOrEmpty(propertyValue))
18                 {
19                     entry.Properties[propertyName].Add(propertyValue);
20                 }
21             }
22         }



原文地址:https://www.cnblogs.com/ycc/p/877797.html