12

我正在尝试使用 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 {"You must call read on the reader before accessing its data."} CsvHelper.CsvHelperException {CsvHelper.CsvReaderException}

4

2 回答 2

17

未使用该插件,但错误消息似乎很清楚。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();
}
于 2012-06-18T16:25:01.427 回答
0

当我尝试以下代码时,我遇到了类似的问题,但解决了

void Main()
{
    using (var reader = new StreamReader("path\\to\\file.csv"))
    using (var csv = new CsvReader(reader, 
           System.Globalization.CultureInfo.CreateSpecificCulture("enUS")))
    {
        var records = csv.GetRecords<Foo>();
    }
}

请注意,下面的代码不适用于最新版本的 CSV Helper

using (var csvReader = new CsvReader(reader))
于 2020-02-07T23:10:15.997 回答