c# – 在文件上传时使用CSVHelper

前端之家收集整理的这篇文章主要介绍了c# – 在文件上传时使用CSVHelper前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用CSVhelper插件来读取上传的CSV文件.这是我的modelBinder类:
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 {“在访问数据之前必须先在读取器上调用read”.)CsvHelper.CsvHelperException {CsvHelper.CsvReaderException}

解决方法

没有使用插件,但错误信息似乎很清楚.在访问结果之前,必须有一个Read()函数调用.尝试将您的代码更改为如下所示:
using (var reader = new StreamReader(file.InputStream))
using (var csvReader = new CsvReader(reader))
{
    csvReader.Read();
    return csvReader.GetRecords<SurveyEmailListModels>().ToArray();
}

猜你在找的C#相关文章