简体   繁体   中英

C# reading a csv file and passing the data

I am working on an app that will create users in AD. Right now I can create one user at a time. What I am trying to do now create users in bulk via a CSV file.

After doing some research it looks like using using Microsoft.VisualBasic.FileIO; and the TextFieldParser is the simplest method of doing this.

This is how the CSV file header will be:

FFirstName,LastName,Description,Password,OU,Group

This is what I have so far:

private void CreateUsers_Click ( object sender, EventArgs e ) {

        using ( TextFieldParser csvReader = new TextFieldParser ( userscsv ) )
        {
            csvReader.TrimWhiteSpace = true;
            csvReader.TextFieldType = FieldType.Delimited;
           // csvReader.SetDelimiters ( new string [] { "," } );
            csvReader.SetDelimiters ( "," );



            // reading column fields 
            string [] colFields = csvReader.ReadFields ( );

            int index_FirstName = colFields.ToList ( ).IndexOf ( "FirstName" );

            while ( !csvReader.EndOfData )
            {
                // reading user fields 
                string [] fieldData = csvReader.ReadFields ( );

                AD_Add_User_to_Group.Biz.AdAcctManagement bt = new Biz.AdAcctManagement ( );

                try
                {
                    bt.CreateUser ( this.oulist.Text, this.txtDisplayName.Text, this.txtPassword.Text, this.txtFirstName.Text, this.txtLastName.Text );


                }
                catch ( Exception ex )
                {
                }
            }
        }
    }

How do I read the values from the CSV and pass it to my method:

bt.CreateUser ( this.oulist.Text, this.txtDisplayName.Text, this.txtPassword.Text, this.txtFirstName.Text, this.txtLastName.Text );

instead of this.txtFirtName.Text, I want to pass the first name from the CSV file.

Let me assume that The CSV file is in the form:

someValue,DisplayName,Password,FirstName,LastName

if so you can use the following code to full-fill the requirement:

foreach (string csvLines in File.ReadAllLines("Path here"))
        {
            //Here  csvItem is each Line in the CSV file
            string[] csvItems = csvLines.Split(',').ToArray();
            bt.CreateUser(csvItems[0], csvItems[1], csvItems[2], csvItems[3], csvItems[4]);
        }

Another easier approach can be to use CsvHelper. You can install it from NuGet and it is quite easy to use and flexible. I started using CsvHelper because it supports type conversion while reading the data and also has lot of other useful features. Below is the sample code for your scenario. You can provide the path of the CSV file on the disk. In most cases I prefer to use Embedded Resource. The code is not compiled but it is enough to give you the ideas,

    var assembly = Assembly.GetExecutingAssembly();     

    var resourceName = "<ProjectName>.<FolderName>.UsersList.csv";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                var csv = new CsvReader(reader);
                csv.Configuration.Delimiter = ",";
                csv.Configuration.HasHeaderRecord = true;
                csv.Configuration.IgnoreHeaderWhiteSpace = true;
                csv.Configuration.IgnoreQuotes = false;
                csv.Configuration.IsHeaderCaseSensitive = false;
                csv.Configuration.ThrowOnBadData = true;
                csv.Configuration.QuoteAllFields = true;

                csv.Configuration.RegisterClassMap<UsersClassMap>();
                csv.Configuration.IgnoreReadingExceptions = true;
                csv.Configuration.SkipEmptyRecords = false;
                List<User> records = csv.GetRecords<User>().ToList();

                foreach (User user in records)
                {
                    bt.Create(user.FFirstName, user.lastName, user.Description, user.Password, user.OU, user.Group);
                }
            }
        }

public class User
    {
        public string FFirstName { get; set; }
        public string LastName { get; set; }
        public string Description { get; set; }
        public string Password { get; set; }
        public string OU { get; set; }
        public string Group { get; set; }
    }

public class UsersClassMap : CsvClassMap<User>
    {
        public UsersClassMap()
        {
               Map(x => x.FFirstName).Index(0).Name("FFirstName");
               Map(x => x.LastName).Index(1).Name("LastName");
               Map(x => x.Description).Index(2).Name("Description");
               Map(x => x.Password).Index(3).Name("Password");            
               Map(x => x.OU).Index(4).Name("OU");    
               Map(x => x.Group).Index(5).Name("Group");    
            }
    }

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