2009-09-03 65 views
1

我有一个糟糕的目录日。 :)创建本地用户

有人能告诉我这有什么问题吗?

groupName = "Monkey"; 
... 
using (DirectoryEntry directoryEntryObject = new DirectoryEntry("WinNT://" + Environment.MachineName, "", "", AuthenticationTypes.Secure)) 
{ 
    using (DirectoryEntry group = directoryEntryObject.Children.Add("CN=" + groupName.Trim(), "group")) 
     { 
      group.Properties["sAMAccountName"].Value = groupName; 
      group.CommitChanges(); 
     } 
} 

我想要做的是创建一个本地帐户。当我按原样尝试这个代码,它崩溃的时候我尝试设置SAM帐户属性:

System.Runtime.InteropServices.COMException occurred 
    Message="The directory property cannot be found in the cache.\r\n" 
    Source="Active Directory" 
    ErrorCode=-2147463153 
    StackTrace: 
     at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.PutEx(Int32 lnControlCode, String bstrName, Object vProp) 
    InnerException: 

如果我注释掉该行,它崩溃与以下承诺:

System.Runtime.InteropServices.COMException occurred 
    Message="The specified username is invalid. (Exception from HRESULT: 0x8007089A)" 
    Source="System.DirectoryServices" 
    ErrorCode=-2147022694 
    StackTrace: 
     at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.SetInfo() 
    InnerException: 

我不知道该怎么考虑Source。我在W2003域中的Vista上,但我试图创建一个本地组,而不是一个活动目录组。

任何想法?我可能错过了明显的东西。我可以使用GroupPricipal.Save方法创建用户,因此它不是权限问题。

回答

3

尝试this code,我敢肯定它会做的伎俩;)

using System; 
using System.DirectoryServices; 

class Class1 
{ 
    static void Main(string[] args) 
    { 
    try 
     { 
    DirectoryEntry AD = new DirectoryEntry("WinNT://" + 
         Environment.MachineName + ",computer"); 
    DirectoryEntry NewUser = AD.Children.Add("TestUser1", "user"); 
    NewUser.Invoke("SetPassword", new object[] {"#12345Abc"}); 
    NewUser.Invoke("Put", new object[] {"Description", "Test User from .NET"}); 
    NewUser.CommitChanges(); 
    DirectoryEntry grp; 

    grp = AD.Children.Find("Guests", "group"); 
    if (grp != null) {grp.Invoke("Add", new object[] {NewUser.Path.ToString()});} 
    Console.WriteLine("Account Created Successfully"); 
    Console.ReadLine(); 
    } 
    catch (Exception ex) 
    { 
    Console.WriteLine(ex.Message); 
    Console.ReadLine(); 

    } 
    } 
}