C# 如何将字节[]转换为模型

C# 如何将字节[]转换为模型,c#,entity-framework,model,stream,C#,Entity Framework,Model,Stream,我读这篇文章是为了用MVC上传一个文件。我已经有了一个InputStream.Read之后的文件,但不知道如何使用它来创建IEnumerable,这样我就可以使用EF将它发送到db。这个文件是CSV文件,我知道它的结构 public class MyViewModel { [Required] public HttpPostedFileBase File { get; set; } } [HttpPost] public ActionResult Index(MyViewMod

我读这篇文章是为了用MVC上传一个文件。我已经有了一个
InputStream.Read
之后的文件,但不知道如何使用它来创建
IEnumerable
,这样我就可以使用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; }
}

将字节转换为字符串

var csv = Encoding.UTF8.GetString(uploadedFile);
然后将CSV解析到模型中

这应该会有很大帮助

var textReader = new StringReader(csv);
var helper = new CsvHelper(textReader);
IEnumerable<PriceViewModel> records = helper.GetRecords<PriceViewModel>();
var textReader=新的StringReader(csv);
var helper=新的CsvHelper(文本阅读器);
IEnumerable records=helper.GetRecords();

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

IEnumerable的用途是什么?您可以直接在模型流中分配字节数组。@AkashKC这就是问题所在。我怎么做到的?该文件是一个csv文件,我知道其结构,因此我想之前分配给该模型的验证过程将是很好的添加,以确保该文件具有正确的结构您可以共享您的EF模型,以便我们了解IEnumerable@AkashKCIs done将字节转换为字符串,然后将CSV解析为模型。从那里您可以验证数据并保存到数据库。CsvHelper应该能帮上大忙好吧,我试试看。但是为什么在另一个问题上他会做
model.File.InputStream.Read
他们正在把数据流中的字节复制到arrayOk中,我在字符串上找到了一些东西。但我的文本包含西班牙语单词,而重音字母则以古怪的符号出现。我是在上传过程中还是在转换过程中损坏了数据?但是
File
MyViewModel
的一部分不是数组你在这里创建了数组
byte[]uploadedFile=new byte[model.File.InputStream.Length]
然后将数据从流复制到该数组中