当前位置:  开发笔记 > 编程语言 > 正文

C#在Active Directory中创建OU

如何解决《C#在ActiveDirectory中创建OU》经验,为你挑选了1个好方法。

我正在努力使用下面的代码为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 =内部,DC = net,DC =内部,DC = net'导致错误,因为域显然不存在.

我的问题是我可以在strPath没有使用的情况下创建OU .Children.Add吗?

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



1> 小智..:

试试这个

using System;
using System.DirectoryServices;

namespace ADAM_Examples
{
    class CreateOU
    {
        /// 
        /// Create AD LDS Organizational Unit.
        /// 
        [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;
    }
}
}

推荐阅读
无名有名我无名_593
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有