Skip to content

Can CsvHelper store the CSV row number in the mapped object? #845

Closed

Description

@reloaded

Hello!

I'm mapping my CSV records to a concrete object and I was wondering if there's a way to persist the row number in the concrete object?

I have a mapped object that looks like this:

public class CsvRowDto {
  public string FirstName {get; set;}
  public string LastName {get; set;}
}

And I'm trying to achieve something like this:

public class CsvRowDto {
  public int RowNumber {get; set;}
  public string FirstName {get; set;}
  public string LastName {get; set;}
}

The use case for this is to provide better error reporting. When my application detects a validation/business rule error I'd like to report the row number that had an error.

var records = csvReader.GetRecords<CsvRowDto>().ToList();

foreach(var person in records) {
  if(string.IsNullOrEmpty(person.FirstName)) {
    Console.WriteLine("First name is invalid: " + person.RowNumber);
  }
}

Activity

  1. JoshClose commented on Nov 15, 2017

    @JoshClose
    Owner

    Text file row number or CSV row number? Meaning, a CSV field may have a \r\n in it.

  2. reloaded commented on Nov 15, 2017

    @reloaded
    Author

    That's a quick response! :)

    I think CSV row number?... I'm not certain on the differences between the two. The text file row number includes blank lines, right?

    Let's say that you are a end user of my application and you upload a CSV. When my system detects an error it needs to tell you which row you should take a look at in the CSV file to find and fix the issue....

    So... I think I need the CSV row number?

  3. JoshClose commented on Nov 15, 2017

    @JoshClose
    Owner

    You'll want the file's line number then. A single CSV row may span many lines because a field could contain a '\r\n'.

    void Main()
    {
        using (var stream = new MemoryStream())
        using (var writer = new StreamWriter(stream))
        using (var reader = new StreamReader(stream))
        using (var csv = new CsvReader(reader))
        {
            writer.WriteLine("Id,Name");
            writer.WriteLine("1,one");
            writer.WriteLine("2,two");
            writer.Flush();
            stream.Position = 0;
            
            csv.Configuration.RegisterClassMap<TestMap>();
            csv.GetRecords<Test>().ToList().Dump();
        }
    }
    
    public class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int RowNumber { get; set; }
    }
    
    public sealed class TestMap : ClassMap<Test>
    {
        public TestMap()
        {
            Map(m => m.Id);
            Map(m => m.Name);
            Map(m => m.RowNumber).ConvertUsing(row => row.Context.RawRow);
        }
    }
  4. JoshClose commented on Nov 15, 2017

    @JoshClose
    Owner

    Also, when an exception occurs, that information is available in the exception too.

  5. reloaded commented on Nov 16, 2017

    @reloaded
    Author

    Wonderful! @JoshClose That solved my question. Using Map(m => m.RowNumber).ConvertUsing(row => row.Context.RawRow); works like a charm.

  6. itscodeminer commented on Oct 18, 2019

    @itscodeminer

    Hi,
    If the content of records span across multiples rows, the actual row number in the document is returned instead of record number, how do we get record number in csv in such a case
    Thank you!

  7. JoshClose commented on Oct 18, 2019

    @JoshClose
    Owner

    Use Row instead of RawRow.

  8. capinredbeard commented on Jan 28, 2021

    @capinredbeard

    Is this still an option? It looks like the API has changed, and ConvertUsing is no longer available. I have also tried to use a TypeConverter, but haven't found a way to get the row number.

    EDIT: Just found the following, which appears to be what I need (untested):
    Map(m => m.LineNumber).Convert(row => row.Context.Parser.RawRow);

  9. JoshClose commented on Jan 29, 2021

    @JoshClose
    Owner

    Yes, ConvertUsing was renamed to Convert.

  10. jzabroski commented on Feb 3, 2021

    @jzabroski

    @JoshClose I think you should convert this to a Discussion and select the answer so that you can update the answer as you progress CsvHelper.

    e.g.,

    v12:

    Map(m => m.LineNumber).ConvertUsing(row => row.Context.RawRow);

    v13 - v20:

    Map(m => m.LineNumber).ConvertUsing(row => row.Context.Row);

    v21:

    Map(m => m.LineNumber).Convert(row => row.Context.Row);
  11. Repository owner locked and limited conversation to collaborators on Feb 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions