【问题标题】:C# Error trying Creating Organizational unit with spaces尝试使用空格创建组织单位时出现 C# 错误
【发布时间】:2017-09-29 08:14:23
【问题描述】:

所以我有一个程序需要在另一个 OU 下添加一个新的组织单位。格式必须与下面的代码相同。问题是,如果我在名称中添加空格,我会不断收到相同的异常。我可以手动添加带有空格的 OU。我在这里做错了什么?

代码如下:

        string ou = "OU=" + "New Company 99999";

        try
        {
            if (DirectoryEntry.Exists("LDAP://" + ou + ",OU=MainOrganizationalUnit,DC=domain,DC=com"))
            {
                MessageBox.Show(ou + " exists.");
            }
            else
            {
                MessageBox.Show(ou + " does not exist. Creating...");

                using (DirectoryEntry entry = new DirectoryEntry("LDAP://OU=MainOrganizationalUnit,DC=domain,DC=com"))
                {
                    using (DirectorySearcher searcher = new DirectorySearcher(entry))
                    {
                        searcher.Filter = "(" + ou + ")";
                        searcher.SearchScope = SearchScope.Subtree;
                        SearchResult result = searcher.FindOne();

                        if (result == null)
                        {
                            /* OU Creation */
                            DirectoryEntry de = entry.Children.Add(ou, "organizationalUnit");
                            de.Properties["description"].Value = "This is a Test";
                            de.CommitChanges();
                        }
                    }
                }
            }
        }
        catch (Exception Ex)
        {
            LogWriter.Exception(Ex);
        }

当我运行此代码时,我会记录以下错误: System.DirectoryServices.DirectoryServicesCOMException (0x80072037):存在命名冲突。

在 System.DirectoryServices.DirectoryEntry.CommitChanges() 在 MyProgram.MyStaticClass.function()

【问题讨论】:

  • 如果SO:C# PrincipalContext Error “Server names cannot contain a space character” 没有帮助,您可以通过string ou = "OU=" + @"""New Company 99999"""; 获得一些东西来摆脱困境
  • @MadMyche 我实际上正在使用单独的解决方法。看来我可以将现有的 OU 重命名为其中带有空格的东西。 DirectoryEntries des = entry.Children;DirectoryEntry badObject = des.Find(ou);badObject.Rename("OU=With Spaces 99999");entry.CommitChanges();

标签: c# active-directory directoryentry organizational-unit


【解决方案1】:

重命名 OU 似乎不是理想的解决方案。 只需尝试使用反斜杠转义空格

string ou = "OU=" + "New\\ Company\\ 99999"; 

This article 显示在将 LDAP 与 AD 一起使用时必须转义的字符。

【讨论】:

  • 谢谢。我实际上换成了一个生成 powershell 脚本并执行该脚本的方法。
【解决方案2】:

所以,我目前正在使用解决方法,但我觉得我不应该这样做。本质上,我现在正在创建一个不带空格的临时 OU 名称,然后重命名它。

DirectoryEntries des = entry.Children;
DirectoryEntry badObject = des.Find(ou);
badObject.Rename("OU=With Spaces 99999");
entry.CommitChanges();

【讨论】:

    猜你喜欢
    • 2023-02-13
    • 2021-09-07
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 2014-07-20
    • 1970-01-01
    相关资源
    最近更新 更多