2009-08-19 153 views
20

我需要在Active Directory中創建一個新用戶。我發現了幾個例子,如下所示:在.NET中創建Active Directory用戶(C#)

using System; 
using System.DirectoryServices; 

namespace test { 
    class Program { 
     static void Main(string[] args) { 
     try { 
      string path = "LDAP://OU=x,DC=y,DC=com"; 
      string username = "johndoe"; 

      using (DirectoryEntry ou = new DirectoryEntry(path)) { 
       DirectoryEntry user = ou.Children.Add("CN=" + username, "user"); 

       user.Properties["sAMAccountName"].Add(username); 

       ou.CommitChanges(); 
      } 
     } 
     catch (Exception exc) { 
      Console.WriteLine(exc.Message); 
     } 
     } 
    } 
} 

當我運行此代碼時,我得到沒有錯誤,但沒有創建新用戶。

我正在運行測試的帳戶具有足夠的權限在目標組織單位中創建用戶。

我是否缺少某些東西(可能是用戶對象的某些必需屬性)?

任何想法爲什麼代碼不會例外?

編輯
以下爲我工作:

int NORMAL_ACCOUNT = 0x200; 
int PWD_NOTREQD = 0x20; 
DirectoryEntry user = ou.Children.Add("CN=" + username, "user"); 
user.Properties["sAMAccountName"].Value = username; 
user.Properties["userAccountControl"].Value = NORMAL_ACCOUNT | PWD_NOTREQD; 
user.CommitChanges(); 

所以實際上有幾個問題:

  1. CommitChanges必須user(感謝羅布)被稱爲
  2. 密碼策略阻止了用戶的創建(感謝Marc)

回答

16

我認爲你正在呼籲錯誤的DirectoryEntry的CommitChanges。在MSDN文檔(http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentries.add.aspx)它規定如下(重點由我加的)

必須調用的CommitChanges方法的新條目使創建永久性的。當你調用這個方法時,你可以在新條目上設置強制屬性值。在調用CommitChanges方法前,每個提供者都有不同的需要設置的屬性需求。如果這些要求不符合,提供者可能會拋出異常。在提交更改之前,請諮詢您的提供商以確定必須設置哪些屬性。

所以,如果你改變你的代碼user.CommitChanges()它應該工作,如果你需要設置不僅僅是帳戶名更多的屬性,那麼你應該得到一個例外。

由於您當前在未更改的OU上調用CommitChanges(),因此不會有例外。

+0

良好的漁獲! :-) – 2009-08-19 08:25:26

+1

閱讀「手冊」的力量:) – balexandre 2009-08-19 09:33:57

8

假設你的OU路徑OU=x,DC=y,DC=com確實存在 - 它應該工作:-)

檢查事項:

  • 您要添加一個值 「的samAccountName」 - 爲什麼不你只需將其值設置:

    user.Properties["sAMAccountName"].Value = username; 
    

否則,你可能會與服務器結束人samAccountNames - 這將無法正常工作.....

  • 你不設置userAccountControl財產的任何東西 - 嘗試使用:

    user.Properties["userAccountControl"].Value = 512; // normal account 
    
  • 你有多個域控制器你的組織?如果你和你使用的是「無服務器」綁定(不在LDAP路徑中指定任何服務器),你可能會驚訝於用戶被創建的位置:-),這將需要幾分鐘長達半小時在整個網絡上同步

  • 您是否有嚴格的密碼策略?也許這就是問題所在。我記得我們以前必須先用「不需要密碼」選項創建用戶,先執行.CommitChanges(),然後創建一個足夠強大的密碼,在用戶上設置它,然後刪除該用戶選項。

馬克

0

檢查下面的代碼

DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local"); 

     for (int i = 3; i < 6; i++) 
     { 
      try 
      { 
       DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i, "user"); 
       childEntry.CommitChanges(); 
       ouEntry.CommitChanges(); 
       childEntry.Invoke("SetPassword", new object[] { "password" }); 
       childEntry.CommitChanges(); 
      } 
      catch (Exception ex) 
      { 

      } 
     } 
相關問題