CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

Retrieve rows as string array

Open TalonZA opened this issue 4 years ago • 3 comments

Is your feature request related to a problem? Please describe. I need to be able to read dynamic csv files where the contents are only partially known. For example, I know the first column will contain a specific key. Other columns may be added or removed without notice.

Describe the solution you'd like Currently, there is an option to retrieve the Header as a string[], but not the body. I would expect an easy way to GetRecords which returns an IEnumerable<string[]>.

Describe alternatives you've considered I have considered manually looping through each row and creating this myself by using getField, but this seems very obscure and prone to error.

TalonZA avatar Apr 13 '21 10:04 TalonZA

If you just want a string[] you can use the parser directly.

void Main()
{
    var s = new StringBuilder();
    s.Append("Id,Name\r\n");
    s.Append("1,one\r\n");
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
    };
    using (var reader = new StringReader(s.ToString()))
    using (var csv = new CsvParser(reader, config))
    {
        while (csv.Read())
        {
            csv.Record.Dump();
        }
    }
}

image

I would suggest using the reader still so you can convert fields.

https://joshclose.github.io/CsvHelper/examples/reading/reading-by-hand

If the columns are the same based on the first field, you can do something like this.

https://joshclose.github.io/CsvHelper/examples/reading/reading-multiple-data-sets

JoshClose avatar Apr 13 '21 15:04 JoshClose

How can I get string array for each row? csv.Record.Dump() throws error "CscReader does not contain definition for Record. I used package id="CsvHelper" version="30.0.1" targetFramework="net472" Checked documentation of CsvHelper, nothing there for getting a row as string[]

luvkushch avatar Sep 13 '23 09:09 luvkushch

How can I get string array for each row? csv.Record.Dump() throws error "CscReader does not contain definition for Record. I used package id="CsvHelper" version="30.0.1" targetFramework="net472" Checked documentation of CsvHelper, nothing there for getting a row as string[]

Example (does not differentiate between header/data rows):

public List<List<string>> GetCsvFileParsed(string path)
{
    var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = "|" };

    using var stringReader = new StringReader(GetCsvFileContent(path));
    using var csvParser = new CsvParser(stringReader, csvConfig);

    List<List<string>> result = new List<List<string>>();
    while (csvParser.Read())
    {
        result.Add(csvParser.Record.ToList());
    }

    return result;
}

sjanisz avatar Feb 20 '24 12:02 sjanisz