Search code examples
c#csvcsvhelper

C# CsvHelper not trimming the spaces in the fields


I'm using CsvHelper http://csvhelper.com version 2.16.3. I want to parse a csv file trimming all the extra spaces in every cell.

this is my failing unit test

    [Fact]
    public void GetNextBatch_should_trim_every_cell()
    {
        var csvService = new CsvService();
        var stream = new MemoryStream();
        var streamWriter = new StreamWriter(stream);
        streamWriter.WriteLine("  123  , hello ");
        streamWriter.Flush();
        stream.Position = 0;

        var csvParser = new CsvParser(new StreamReader(stream, true), new CsvConfiguration
        {
            IsHeaderCaseSensitive = false,
            SkipEmptyRecords = true,
            TrimFields = true,
            TrimHeaders = true
        });

        var res = csvService.GetNextBatch(csvParser, 10);
        Assert.Equal("123", res.First()[0]);
        Assert.Equal("hello", res.First()[1]);
    }

    public IEnumerable<string[]> GetNextBatch(CsvParser csvParser, int batchSize)
    {
        var list = new List<string[]>();
        while (list.Count < batchSize)
        {
            var rows = csvParser.Read();
            if (rows == null)
                break;
            list.Add(rows);
        }
        return list;
    }

When I run the test this is the result

Assert.Equal() Failure ↓ (pos 0) Expected: 123 Actual: 123
↑ (pos 0)

What I'm I doing wrong? Thanks


Solution

  • I was using the library in a wrong way, instead of CsvParser I should use CsvReader as suggested in the documentation.