Home > Back-end >  CSVHelper change/ manipulate headers before reading the csv
CSVHelper change/ manipulate headers before reading the csv

Time:11-28

Am not in control of what csv file we may get and they ted to have an extra '_' or year added to the name from time to time which does not match with the mapping I have done. Tried

var config = new CsvConfiguration(cultureInfo)
              {
                  PrepareHeaderForMatch = args => args.Header.Replace("_", " "),
              };
config.PrepareHeaderForMatch = args => Regex.Replace(args.Header, @"2021", string.Empty);
List<CSVInvoiceLineDetail> CSVParsedDataList = new();
using TextReader reader = new StreamReader(file.OpenReadStream());
using var csv = new CsvReader(reader, config);
csv.Read();
csv.ReadHeader();
while (csv.Read())
{                             
    CSVParsedDataList.Add(csv.GetRecord<CSVInvoiceLineDetail>());
    // Do something with the record.
}

but it doesn't work the headers are still how they were originally. Can anyone point out what am doing wrong here ?

CodePudding user response:

Consider

          var config = new CsvConfiguration(cultureInfo)
          {
              PrepareHeaderForMatch = args => args.Header.Replace("_", " ").Replace("2021","");,
          };

Or if you want to strip all numbers and underscores out of headers:

          var config = new CsvConfiguration(cultureInfo)
          {
              PrepareHeaderForMatch = args => Regex.Replace(args.Header, "[0-9_]", "")
          };

Note that here it is replacing underscore with nothing, not space, so some adjustment to your declared header attributes may be required

  • Related