C#在Active Directory中创建OU

时间:2008-12-30 16:10:22

标签: c# active-directory

我正在努力使用以下代码为Active Directory创建OU。

strPath = "OU=TestOU,DC=Internal,DC=Com"

DirectoryEntry objOU; 
objOU = ADentry.Children.Add(strPath, "OrganizationalUnit");
objOU.CommitChanges();

问题是strPath包含完整路径'OU = TestOU,DC = Internal,DC = net'所以使用.Children.Add使ldap路径'OU = TestOU,DC = Internal,DC = net,DC =内部,DC = net',这会导致错误,因为域显然不存在。

我的问题是,我可以使用strPath创建OU而不使用.Children.Add吗?

我不熟悉AD,这是我从我之前的那个人那里继承的。

3 个答案:

答案 0 :(得分:13)

试试这个

using System;
using System.DirectoryServices;

namespace ADAM_Examples
{
    class CreateOU
    {
        /// <summary>
        /// Create AD LDS Organizational Unit.
        /// </summary>
        [STAThread]
        static void Main()
        {
            DirectoryEntry objADAM;  // Binding object.
            DirectoryEntry objOU;    // Organizational unit.
            string strDescription;   // Description of OU.
            string strOU;            // Organiztional unit.
            string strPath;          // Binding path.
        // Construct the binding string.
        strPath = "LDAP://localhost:389/O=Fabrikam,C=US";

        Console.WriteLine("Bind to: {0}", strPath);

        // Get AD LDS object.
        try
        {
            objADAM = new DirectoryEntry(strPath);
            objADAM.RefreshCache();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error:   Bind failed.");
            Console.WriteLine("         {0}", e.Message);
            return;
        }

        // Specify Organizational Unit.
        strOU = "OU=TestOU";
        strDescription = "AD LDS Test Organizational Unit";
        Console.WriteLine("Create:  {0}", strOU);

        // Create Organizational Unit.
        try
        {
            objOU = objADAM.Children.Add(strOU,
                "OrganizationalUnit");
            objOU.Properties["description"].Add(strDescription);
            objOU.CommitChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error:   Create failed.");
            Console.WriteLine("         {0}", e.Message);
            return;
        }

        // Output Organizational Unit attributes.
        Console.WriteLine("Success: Create succeeded.");
        Console.WriteLine("Name:    {0}", objOU.Name);
        Console.WriteLine("         {0}",
            objOU.Properties["description"].Value);
        return;
    }
}
}

答案 1 :(得分:4)

使用System.DirectoryServices创建对象的唯一方法是为父级创建DirectoryEntry对象并使用DirectoryEntry.Children.Add。

我认为此时你最好的举动是使用你拥有的路径并提取你需要的部分(“OU =某事”)。

答案 2 :(得分:1)

不,你不能。但是你的代码中有一些错误,试试这个:

 string rootOU = @"LDAP://DC=Internal,DC=Com/OU=Root OU,DC=Internal,DC=Com; // or simply "DC=Internal,DC=Com" instead of "OU=Root OU,DC=Internal,DC=Com" if you want to create your test OU in root
 DirectoryEntry objAD = new DirectoryEntry(rootOU, userName, password);
 DirectoryEntry objOU = objAD.Children.Add("OU=Test OU", "OrganizationalUnit");
 objOU.CommitChanges();