2012-06-18 10 views
9

Próbuję użyć wtyczki CSVhelper, aby odczytać przesłany plik CSV. Oto moja klasa modelBinder:Używanie CSVHelper przy przesyłaniu plików

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

Są to obiekty Próbuję map do:

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

} 

Wewnątrz Visual Studio debugera ja dostaję błąd:

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

Odpowiedz

14

Nie użyłem wtyczki, ale komunikat o błędzie wydaje się całkiem jasny. Aby uzyskać dostęp do wyników, należy wywołać funkcję Read(). Zmień kod na mniej więcej taki:

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

Doh! To wystarczyło - dziękuję za pomoc, podczas gdy mój mózg przyspiesza dziś rano. – user547794

+0

Bez problemu. Miło, że mogłem pomóc. –

+0

Ale nie ma wywołania Read() w twoim kodzie – cyberspy

Powiązane problemy