jeudi 8 novembre 2018

I am reading a CSV file and generating the file

I am using some refactored help on generating dynamic classes, that mirror a CSV files headers I am reading.

Question: How do I dynamically name/emit the class name using the file name, and write the below Customer.cs class to disk. at runtime ?


string dirForCSVfiles; // user selected file
//ctrllr
[HttpPost]
public ActionResult UserSelectedFile(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
    dirForCSVfiles = path; //CSV path including the filename
  }

  return RedirectToAction("Index");
}


//build dynamic class
public List<TModel> ReadCsvFile<TModel, TModelMapper>(string file) where TModelMapper : ClassMap<TModel>
{
    var configuration = new Configuration
    {
        IncludePrivateMembers = false,
        IgnoreBlankLines = true,
        Delimiter = ";" // You may want to change this
    };
    configuration.RegisterClassMap<TModelMapper>();
    using (var csvFile = File.OpenText(file))
    {
        var parser = new CsvHelper.CsvReader(csvFile, configuration);
        return parser.GetRecords<TModel>().ToList();
    }
}


// Then you reading the file like this
//************************************//
// Question -- how do I REPLACE the `CustomerModel` part to be REFLECTED extracted or name after the CSV filename???
var customers = ReadCsvFile<CustomerModel, CustomerModelMapper>(@"customers.csv");





Aucun commentaire:

Enregistrer un commentaire