Search code examples
csvhelper

How to tell where the file had an issue when CSVHelper throws with bad data?


I am convinced that part of my file had some issues, and csvHelper is throwing on BadDataFound.

But how do I tell where the issue is? Using some online csv parsers seem to parse my file just fine.

Below is how I am using csvParser

public ICollection<FileRecord> FromCsv(string csv)
{
    var csvWithHeader = CrowdinFileRecord.Scheme + Environment.NewLine + csv;
    using (var stream = new MemoryStream())
    using (var reader = new StreamReader(stream))
    using (var writer = new StreamWriter(stream))
    using (var csvReader = new CsvReader(reader))
    {
        csvReader.Configuration.HasHeaderRecord = true;
        csvReader.Configuration.RegisterClassMap<FileRecordMap>();
        writer.Write(csvWithHeader);
        writer.Flush();
        stream.Position = 0;
        return csvReader.GetRecords<FileRecord>().ToList();
    }
}

Solution

  • This will at least give you a better idea of where the issue is.

    try
    {
        return csvReader.GetRecords<FileRecord>().ToList();
    }
    catch (BadDataException ex)
    {
        throw new Exception($"BadDataException at RawRow: {ex.ReadingContext.RawRow}, RawRecord: {ex.ReadingContext.RawRecord}", ex);
    }