为了账号安全,请及时绑定邮箱和手机立即绑定

如何将byte []转换为模型

如何将byte []转换为模型

C#
慕标5832272 2021-05-17 17:34:40
我正在阅读此答案以使用MVC上传文件。我已经在a之后有了文件,InputStream.Read但是不知道如何使用它来创建文件,IEnumerable<MyModel>因此我可以使用EF将其发送到db。该文件是CSV文件,我知道其结构。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");}我的模特:public class PriceViewModel{            public int PriceId { get; set; }    public int? YearSelected { get; set; }    public int? WeekSelected { get; set; }    public int? StateSelected { get; set; }}
查看完整描述

1 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

将字节转换为字符串


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

然后将CSV解析为模型。


CsvHelper应该对此提供很多帮助。


var textReader = new StringReader(csv);

var helper = new CsvHelper(textReader);

IEnumerable<PriceViewModel> records = helper.GetRecords<PriceViewModel>();

从那里您可以验证数据并保存到数据库。


查看完整回答
反对 回复 2021-05-23
  • 1 回答
  • 0 关注
  • 196 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信