質問

I am trying to use the CSVhelper plugin to read an uploaded CSV file. Here is my modelBinder class:

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();
        }
    }
}

These are the objects I am trying to map to:

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; }

}

Inside the Visual Studio debugger I am getting an error:

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

役に立ちましたか?

解決

Not used the plugin but the error message seems pretty clear. There must be a Read() function to call before accessing the results. Try changing your code to something like this:

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();
}

他のヒント

I had similar issue , but sorted out, when I tried the below code

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>();
    }
}

Please note below code wont work with latest versions of CSV Helper

using (var csvReader = new CsvReader(reader))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top