Получение сообщения об ошибке "индекс был вне диапазона" при попытке добавить пользователей в группу в ad через C#
Ниже приведен код, который я использую для создания рекламных аккаунтов, я дошел до их создания, но когда я пытаюсь добавить их в группу в качестве члена, я получаю сообщение об ошибке out of range.
Проблема заключается в последней части кода, где он добавляет пользователя, которого я только что создал, в указанную мной группу объявлений, но именно здесь он терпит неудачу.
Я немного новичок в c#, поэтому у меня возникли проблемы с выяснением того, что здесь не так, любая помощь будет очень признательна
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; using System.DirectoryServices; using System.Collections; using Microsoft.VisualBasic.FileIO; namespace ADBulkImport { public partial class FrmBulkImport : Form { public FrmBulkImport() { InitializeComponent(); } private void BtnBulkImport_Click(object sender, EventArgs e) { //Path to OU , currently using test students var strPath = "LDAP://OU=Test Students,OU=Users,OU=Client Services,DC=esc,DC=local"; //reading csv var csvFilePath = @"T:\jake\Account creator messing\test files\StudentAccount.csv"; using (TextFieldParser csvReader = new TextFieldParser(csvFilePath, System.Text.Encoding.Default)) { //to be used if the reports needs to used fields e.g. firstname , surname ,coursecode //csvReader.CommentTokens = new string[] { "#" }; csvReader.SetDelimiters(new string[] { "," }); csvReader.HasFieldsEnclosedInQuotes = true; csvReader.ReadLine(); //dispaly csv list in the lsit veiw //StudentList while (!csvReader.EndOfData) { // reading column fields string[] colFields = csvReader.ReadFields(); string index_GivenName = colFields[0]; string index_Surname = colFields[1]; string index_ID = colFields[2]; string index_Course = colFields[3]; string index_Department = colFields[4]; int intNoOfUsersForEachOU = 500; int intNoOfMembersForEachGroup = 500; //while (!csvReader.EndOfData) try { // DirectoryEntry adStudentFolder = new DirectoryEntry("LDAP://OU=Test Students,OU=Users,OU=Client Services,DC=esc,DC=local"); ArrayList objUserList = new ArrayList(); string st = File.ReadAllText(csvFilePath); string email = index_ID + "@student.esc.ac.uk"; //set the home drive string homeDirectoryLocation = "\\\\escfile01.esc.local\\stuhome$\\" + index_ID; string ArthomeDirectoryLocation = "\\\\escfile01.esc.local\\arthome$\\" + index_ID; var strUserName = index_GivenName + " " + index_Surname + " " + index_ID; //ArrayList objUserList = new ArrayList(); Console.WriteLine(st); DirectoryEntry objDEUser = new DirectoryEntry(strPath); DirectoryEntry objUser = objDEUser.Children.Add("CN=" + strUserName, "user"); // User name (domain based) objUser.Properties["userprincipalname"].Add(index_ID + "@student.esc.ac.uk"); // User name (older systems) objUser.Properties["samaccountname"].Add(index_ID); // Surname objUser.Properties["sn"].Add(index_Surname); // Forename objUser.Properties["givenname"].Add(index_GivenName); // Display name objUser.Properties["displayname"].Add(index_GivenName + " " + index_Surname + " " + index_ID); // Description objUser.Properties["description"].Add(index_Course); //Department objUser.Properties["department"].Add(index_Department); //just says student in the job title objUser.Properties["title"].Add("Student"); //company objUser.Properties["company"].Add(index_Course); // E-mail objUser.Properties["mail"].Add(email); //add student group objUserList.Add(index_ID); // Add the user to the students group // Reset the password //resetPassword(sUserName, sPassword, forcePwdChange); // needs to check with the course code to see if it needs to apply the stu home or the art home. if (index_Department == "AAD") { //Home Folder objUser.Properties["HomeDrive"].Add("Y:"); objUser.Properties["HomeDirectory"].Add(ArthomeDirectoryLocation); } else { //Home Folder objUser.Properties["HomeDrive"].Add("Y:"); objUser.Properties["HomeDirectory"].Add(homeDirectoryLocation); } objUser.CommitChanges(); objDEUser.CommitChanges(); objUser.Invoke("SetPassword", new object[] { "College1945" }); objUser.CommitChanges(); //Password // objUser.Invoke("SetPassword", new object[] { "letmein123" }); //objUser.CommitChanges(); //enable user account int val = (int)objUser.Properties["userAccountControl"].Value; objUser.Properties["userAccountControl"].Value = val & ~0x0002; objUser.CommitChanges(); objUser.Dispose(); //Adding user to the recenlty created group as member //strPath = "LDAP://" + "yourdomain.com/" + "CN=" + strGroupName + ",OU=" + strOUName + ",OU=" + strMainOU + "," + strPostPath; //Adding members to Group ArrayList objGroupUserList = new ArrayList(); for (int indexUser = 1; indexUser <= intNoOfMembersForEachGroup; indexUser++) { //Getting random user from List Random rnd = new Random(); int randomUser = rnd.Next(1, intNoOfUsersForEachOU); string strGroupUser = Convert.ToString(objUserList[randomUser]); //If user is already exist in group then skip that user if (objGroupUserList.Contains(strGroupUser)) { continue; } //var strPath = "LDAP://OU=Test Students,OU=Users,OU=Client Services,DC=esc,DC=local"; var ustr = "CN=Test Students,OU=Exceptions And Queries,OU=Students,OU=Users,OU=Client Services,DC=esc,DC=local"; DirectoryEntry ent = new DirectoryEntry(strPath); ent.Properties["member"].Add(ustr); ent.CommitChanges(); objGroupUserList.Add(strGroupUser); } } catch (Exception ex) { MessageBox.Show(ex.Message); //MessageBox.Show("Failed ..."); Console.WriteLine(ex.ToString()); Console.WriteLine(System.Runtime.InteropServices.Marshal.GetExceptionCode()); } } } } } }
Что я уже пробовал:
Получение сообщения об ошибке "индекс был вне диапазона должен быть неотрицательным и меньше размера коллекции" при попытке добавить пользователей в группу в AD через c#
CHill60
Явно какая строка вызывает исключение? Использовали ли вы методы отладки для проверки значений и размеров используемых элементов … Освоение отладки в Visual Studio 2010 - руководство для начинающих[^]