日期:2014-05-17  浏览次数:21423 次

使用C#操作WindowAD之Windows用户组

?

public void CreateWindowsGroup(String groupName, String groupDesc, int groupCtl)
{
     String ladpRootPath = "LDAP://192.168.213.168/CN=Users,DC=pk1,DC=cctv,DC=com";
     DirectoryEntry ladpRoot = new DirectoryEntry(ladpRootPath);
     ladpRoot.Username = "XXXXX";
     ladpRoot.Password = "XXXXX";
     DirectoryEntry group = ladpRoot.Children.Add("CN=" + groupName, "group");
     group.Properties["sAMAccountName"].Value = groupName;
     group.Properties["description"].Value = groupDesc;
     group.Properties["groupType"].Value = groupCtl;
     group.CommitChanges();
     group.Close();
}

?

?

上述代码用于在AD上创建一个用户组,值得注意的是如果你的程序是放在域控上面执行的,那么 ladpRoot.Username和ladpRoot.Password就不能赋值。另外ladpRootPath是ladp的路径写法,LDAP://192.168.213.168表示你要操作的主机地址,?DC=pk1,DC=cctv,DC=com表示要操作的Windows域,CN=Users表示在windows域的主目录下的Users容器对象。方法参数groupCtl表示一些用户组的类别,包含组别和作用域两种含义,对于组别,分为通讯组和安全组,如果是安全组,值应该为-2147483648,否则为0.对于作用域,分为本地组、全局组和通用组,对应的值分别为0x4、0x2和0x8。groupCtl的值就应该 [组别值] | [作用域值]。

?

下面给出一些常用的用户操作代码:

?

修改用户组信息:

?

?

public void ModifyWindowsGroup(String groupName, String groupDesc, int groupCtl)
{
     String ladpRootPath = "LDAP://192.168.213.168/CN=Users,DC=pk1,DC=cctv,DC=com";
     DirectoryEntry ladpRoot = new DirectoryEntry(ladpRootPath);
     ladpRoot.Username = "XXXXX";
     ladpRoot.Password = "XXXXX";
     DirectoryEntry group = ladpRoot.Children.Find("CN=" + groupName, "group");
     group.Properties["description"].Value = groupDesc;
     group.Properties["groupType"].Value = groupCtl;
     group.CommitChanges();
     group.Close();
}

?

删除用户组信息:

?

?

public void DeleteWindowsGroup(String groupName)
{
     String ladpRootPath = "LDAP://192.168.213.168/CN=Users,DC=pk1,DC=cctv,DC=com";
     DirectoryEntry ladpRoot = new DirectoryEntry(ladpRootPath);
     ladpRoot.Username = "XXXXX";
     ladpRoot.Password = "XXXXX";
     DirectoryEntry group = ladpRoot.Children.Add("CN=" + groupName, "group");
     group.DeleteTree();
     group.CommitChanges();
     group.Close();
}