CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

need the position of pointer in memory or simply the line number

Open ImSnehaChawla opened this issue 3 years ago • 4 comments

Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like A clear and concise description of what you want to happen.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context Add any other context or screenshots about the feature request here.

ImSnehaChawla avatar Jan 31 '22 15:01 ImSnehaChawla

When reading? Are you reading using var records = csv.GetRecords<Foo>(); or looping manually like while (csv.Read())?

JoshClose avatar Jan 31 '22 20:01 JoshClose

I would like the answer to this, as well.

I need to enumerate a potentially very large CSV. It'd be nice to know the "row number" (and possibly a way to resume from that number later).

DaleyKD avatar May 05 '22 15:05 DaleyKD

You can get that info from the parser. csv.Parser.

void Main()
{
    var s = new StringBuilder();
    s.Append("Id,Name\r\n");
    s.Append("1,\"one\r\ntwo\"");
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
    };
    using (var reader = new StringReader(s.ToString()))
    using (var csv = new CsvReader(reader, config))
    {
        while (csv.Read())
        {
            var record = csv.GetRecord<Foo>();
            record.Dump();
            csv.Parser.Row.Dump();
            csv.Parser.RawRow.Dump();
        }
    }
}

private class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

image

JoshClose avatar May 05 '22 15:05 JoshClose

If you want to start back on a specific row, you can do something like:

void Main()
{
    var s = new StringBuilder();
    s.Append("Id,Name\r\n");
    s.Append("1,\"one\r\nfoo\"\r\n");
    s.Append("2,\twowo\r\n");
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
    };
    using (var reader = new StringReader(s.ToString()))
    using (var csv = new CsvReader(reader, config))
    {
        var lineToStartOn = 2;
        csv.Read();
        csv.ReadHeader();        
        for (var i = 0; i < lineToStartOn - 1; i++)
        {
            csv.Read();
        }
        
        while (csv.Read())
        {
            var record = csv.GetRecord<Foo>();
            record.Dump();
            csv.Parser.Row.Dump();
            csv.Parser.RawRow.Dump();
            
        }
    }
}

private class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

It needs to subtract 1 because of reading the header row.

JoshClose avatar May 05 '22 16:05 JoshClose