C#Active Directory,为LDAP路径中的每个OU创建组织单位?

时间:2008-12-30 23:03:09

标签: c# active-directory

我正在尝试为LDAP路径中的每个OU创建一个组织单位,如果OU不存在,程序不知道OU名称或OU有多深,则可能有1个OU路径或10深。

实施例: strPath =“OU = Test1,OU = Test2,OU = Test3,DC =内部,DC =净”

下面的代码从strPath中提取最后一个OU'OU = Test1'并创建OU,我遇到的一个大问题是,如果Test2和Test3也不存在,该怎么办?我需要先创建父OU。有没有人就我如何解决这个问题提出任何建议?

DirectoryEntry parent;
String strOU = strPath.Substring(0, strPath.IndexOf(@","));
objOU = parent.Children.Add(strOU, "OrganizationalUnit");
objOU.CommitChanges();

我已尝试将split方法与数组一起使用,但我最终只是在根中创建的每个OU而不是嵌套的OU。问题是路径中的最后一个OU(上面的Test3)需要先创建。我还需要记住Test3可能存在!

1 个答案:

答案 0 :(得分:1)

这是关于如何做到这一点的一些伪代码。您只需要保持从Test3到Test1的每个OU的前置。有点粗糙,希望它有意义。

string strPath = "OU=Test1,OU=Test2,OU=Test3,DC=Internal,DC=net";
// get just DC portion of distinguished name
int dcIndex = strPath.IndexOf("DC=");
string dcSubString = strPath.Substring(dcIndex);
// get just OU portion of distinguished name
string ouSubString = strPath.Substring(0, dcIndex -1);
string tempDistinguishedName = dcSubString;
string[] ouSubStrings = ouSubString.Split(','); 
for (int i = ouSubStrings.Length - 1; i >= 0; i--)
{
    // bind
    DirectoryEntry parentEntry = new DirectoryEntry(tempDistinguishedName);
    // Create OU
    DirectoryEntry newOU = parentEntry.Children.Add(ouSubStrings[i], "OrganizationalUnit");
    newOU.CommitChanges();
    // create distinguishedName for next bind        
    tempDistinguishedName = ouSubStrings[i] + "," + tempDistinguishedName;
    // clean up unmanaged resources
    newOU.Dispose();
    parentEntry.Dispose(); 
}
相关问题