在文件上传使用CSVHelper(Using CSVHelper on file upload)

2019-06-25 13:30发布

我试图用CSVhelper插件读取上传CSV文件。 这里是我的模型绑定器类:

public class SurveyEmailListModelsModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var csv = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var file = ((csv.RawValue as HttpPostedFileBase[]) ?? Enumerable.Empty<HttpPostedFileBase>()).FirstOrDefault();

        if (file == null || file.ContentLength < 1)
        {
            bindingContext.ModelState.AddModelError(
                "",
                "Please select a valid CSV file"
            );
            return null;
        }

        using (var reader = new StreamReader(file.InputStream))
        using (var csvReader = new CsvReader(reader))
        {
            return csvReader.GetRecords<SurveyEmailListModels>().ToArray();
        }
    }
}

这些都是我试图映射到对象:

public class SurveyEmailListModels
{
    [Key]
    [CsvField(Ignore = true)]
    public int SurveyEmailListId { get; set; }

    [CsvField(Index = 0)]
    public int ProgramId { get; set; }

    [CsvField(Index = 1)]
    public virtual SurveyProgramModels SurveyProgramModels { get; set; }

    [CsvField(Index = 2)]
    public string SurveyEmailAddress { get; set; }

    [CsvField(Index = 3)]
    public bool SurveyResponded { get; set; }

}

在Visual Studio调试器中,我得到一个错误:

  • base {"You must call read on the reader before accessing its data."} CsvHelper.CsvHelperException {CsvHelper.CsvReaderException}

Answer 1:

未使用的插件,但该错误消息似乎非常清楚。 必须有一个Read()函数访问的结果之前调用。 试着改变你的代码是这样的:

using (var reader = new StreamReader(file.InputStream))
using (var csvReader = new CsvReader(reader))
{
    // Use While(csvReader.Read()); if you want to read all the rows in the records)
    csvReader.Read();
    return csvReader.GetRecords<SurveyEmailListModels>().ToArray();
}


文章来源: Using CSVHelper on file upload