简体   繁体   中英

Active Directory: System.DirectoryServices namespace. Getting “An invalid directory pathname was passed”

Following the Howto: (Almost) Everything In Active Directory via C# tutorial I'm attempting write a piece to add users to Active Directory using the System.DirectoryServices namespace but I'm getting the error mentioned in the title with each attempt.

As the error suggests, I took a look at how my path-name was structured but I have my doubts still yet.

My goal is to add a new user and place the user in an AD group. Technically, our "Groups" are really just Organizational Units under the parent DC.

Our AD hierarchy is normally formatted as such...

广告样本

OU(Department Name) > OU (Users) > CN(User)

I would also assume that I can set certain properties to the user as I add their new account, although I'm not sure what the limitations are to this.

Below is the code I've written. I've been over a few articles asside from the one on Code Project but I'm not sure if this is just my lack of understanding or what. Surely it's not as difficult as what I'm making it out to be. I may not understand enough about AD just yet.

public static string CreateUserAccount()
    {
        try
        {
            DirectoryEntryData newUserADdata = new DirectoryEntryData();
            string oGUID = string.Empty;

            string connectionPrefix = "LDAP://" + "DOMAIN";
            DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
            DirectoryEntry newUser = dirEntry.Children.Add

                // Define directory entry based on Organizational Units and Common Names
                ("CN=" + newUserADdata.NewUserFirstName + newUserADdata.NewUserLastName + ", OU = " + newUserADdata.NewUserOrganizationDepartment + ", DC = domain, DC = local", "user");

            // Prepair Data for New Entry

            // Initial Login Information
            newUser.Properties["samAccountName"].Value = newUserADdata.NewUserLoginUserName;                                 // Set Initial Username
            newUser.Invoke("SetPassword", new object[] { newUserADdata.NewUserLoginPassword });                              // Set Initial Password
            newUser.Properties["userPrincipalName"].Value = newUserADdata.NewUserLoginUserName + "@domain.local";            // Principal Name
            newUser.Properties["pwdLastSet"].Value = "0";                                                                    // Set "Password Last Set" property to 0 to invoke a password change upon first login


            // General
            newUser.Properties["givenName"].Value = newUserADdata.NewUserFirstName;                                          // First name
            newUser.Properties["sn"].Value = newUserADdata.NewUserLastName;                                                  // Last Name
            newUser.Properties["displayName"].Value = newUserADdata.NewUserDisplayName;                                      // Display Name
            newUser.Properties["description"].Value = newUserADdata.NewUserDescription;                                      // Description
            newUser.Properties["physicalDeliveryOfficeName"].Value = newUserADdata.NewUserOffice;                            // Office
            newUser.Properties["telephoneNumber"].Value = newUserADdata.NewUserTelephone;                                    // Telephone Number
            newUser.Properties["homeDrive"].Value = newUserADdata.NewUserHomeDriveLetter;                                    // Home Drive Letter (H:)
            newUser.Properties["homeDirectory"].Value = newUserADdata.NewUserHomeDrivePath;                                  // Home Drive Path

            // Telephones
            newUser.Properties["homePhone"].Value = newUserADdata.NewUserTelephoneHome;                                      // Home Phone Number
            newUser.Properties["pager"].Value = newUserADdata.NewUserTelephonePager;                                         // Pager Number
            newUser.Properties["mobile"].Value = newUserADdata.NewUserTelephoneMobile;                                       // Mobile Phone Number
            newUser.Properties["facsimileTelephoneNumber"].Value = newUserADdata.NewUserTelephoneFax;                        // Fax Number
            newUser.Properties["ipPhone"].Value = newUserADdata.NewUserTelephoneIP;                                          // IP Phone Number

            // Address
            newUser.Properties["streetAddress"].Value = newUserADdata.NewUserAddressStreet;                                  // Street
            newUser.Properties["postOfficeBox"].Value = newUserADdata.NewUserAddressPObox;                                   // P.O. Box
            newUser.Properties["l"].Value = newUserADdata.NewUserAddressCity;                                                // City
            newUser.Properties["st"].Value = newUserADdata.NewUserAddressState;                                              // State/Province
            newUser.Properties["postalCode"].Value = newUserADdata.NewUserAddressZipCode;                                    // Zip/Postal Code
            newUser.Properties["c"].Value = newUserADdata.NewUserAddressCountry;                                             // Country/Region Name

            // Organization
            newUser.Properties["title"].Value = newUserADdata.NewUserOrganizationJobTitle;                                   // Job Title
            newUser.Properties["department"].Value = newUserADdata.NewUserOrganizationDepartment;                            // Deparment
            newUser.Properties["company"].Value = newUserADdata.NewUserOrganizationCompany;                                  // Company
            newUser.Properties["manager"].Value = newUserADdata.NewUserOrganizationManagerName;                              // Manager Name



            newUser.CommitChanges();
            oGUID = newUser.Guid.ToString();


            int val = (int)newUser.Properties["userAccountControl"].Value;

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
            /// Account Control Flags :: syntax ::  val | hex | hex | and so on...  http://support.microsoft.com/kb/305144
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////

            newUser.Properties["userAccountControl"].Value = val | 512; // Normal User Settings
            newUser.CommitChanges();
            dirEntry.Close();
            newUser.Close();
        }
        catch (System.DirectoryServices.DirectoryServicesCOMException e)
        {
            return "<br /><br /><div class='alert alert-danger'><b><i class='fa fa-exclamation-triangle'></i> An Error has occured:</b> <br /><br />" + e.ToString() + "</div>";

        }
        return "<br /><br /><div class='alert alert-success'><b>Success:<b> <br /><br />The User has been successfully added to Active Directory.</div>";
    }

Any idea how I might get this to work? I really appreciate it.


Update:


For those of you lead to this post by your search for AD solutions..

I've gone with the solution proposed by marc_s. This makes things much easier and speed development along. One item worth mentioning is that the UserPrincipal class properties are a bit limiting. The solution i found for that is to use Principal Extensions . This will allow you to add additional properties to the class that are not included such as physicalDeliveryOfficeName or maybe facsimileTelephoneNumber for example.

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }

    // add a new user
    UserPrincipal newUser = new UserPrincipal(ctx);

    // set properties
    newUser.givenName = "....";
    newUser.surname = "....";
    .....

    // save new user
    newUser.Save();
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM