简体   繁体   中英

How convert byte[] into a model

I'm reading this answer to upload a file using MVC. I already have the file after a InputStream.Read but don't know how use it to create the IEnumerable<MyModel> so I can send it to db using EF. The file is a CSV file, I know the structure of.

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    byte[] uploadedFile = new byte[model.File.InputStream.Length];
    model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length);

    // now you could pass the byte array to your model and store wherever 
    // you intended to store it

    return Content("Thanks for uploading the file");
}

My Model:

public class PriceViewModel
{        
    public int PriceId { get; set; }

    public int? YearSelected { get; set; }
    public int? WeekSelected { get; set; }
    public int? StateSelected { get; set; }
}

Convert the bytes to string

var csv = Encoding.UTF8.GetString(uploadedFile);

and then parse the CSV into the models.

CsvHelper should help a lot with that.

var textReader = new StringReader(csv);
var helper = new CsvHelper(textReader);
IEnumerable<PriceViewModel> records = helper.GetRecords<PriceViewModel>();

From there you can validate the data and save to database.

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