1

I am having a bad directory day. :)

Could someone tell me what is wrong with this?

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();
       }
}

What i am trying to do is create a local account. When I try this code as is, it crashes when I try to set the samaccountname property:

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:

If I comment out that line, it crashes on commit with the following:

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: 

I am not sure what to think about the Source. I am on a Vista in a W2003 domain, but I'm trying to create a local group, not an active directory group.

Any ideas? I probably missed something obvious. I can create users using the GroupPricipal.Save method, so it is not a permissions issue.

1 Answer 1

3

Try this code, I'm pretty sure it will do the trick ;)

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();

    }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.