using csvhelper (nuGET) with C# MVC to import CSV files

Andrew picture Andrew · Mar 31, 2011 · Viewed 21.2k times · Source

https://joshclose.github.io/CsvHelper/ available via NuGet is used to read and write CSV files.

CsvHelper allows you to read your CSV file directly into your custom class.

As following was shown in a previous question

var streamReader = // Create a reader to your CSV file.
var csvReader = new CsvReader( streamReader );
List<MyCustomType> myData = csvReader.GetRecords<MyCustomType>();

CsvReader will automatically figure out how to match the property names based on the header row (this is configurable). It uses compiled expression trees instead of reflection, so it's very fast.

It is also very extensible and configurable.

I'm basically trying to work out how to read in a CSV file with headers (unknown names) and read the records into a custom object.

There is no documentation on this at all so wondered if anyone knew how to use CsvReader to put the values in order into an array of strings or how would you recommend dealing with this?

Answer

Andrew picture Andrew · May 6, 2011

This is my first version, I will update as I amend things and make it more complete but this gives me all the data in string arrays.

   [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {

            ICsvParser csvParser = new CsvParser(new StreamReader(file.InputStream));
            CsvReader csvReader = new CsvReader(csvParser);
            string[] headers = {};
            List<string[]> rows = new List<string[]>();
            string[] row;
            while (csvReader.Read())
            {
                // Gets Headers if they exist
                if (csvReader.HasHeaderRecord && !headers.Any())
                {
                    headers = csvReader.FieldHeaders;
                }
                row = new string[headers.Count()];
                for (int j = 0; j < headers.Count(); j++)
                {
                    row[j] = csvReader.GetField(j);
                }
                rows.Add(row);
            }
            ImportViewModel model = new ImportViewModel(rows);
            return View(model);
        }