Csv Helper 不匹配具有 PrepareHeaderForMatch 设置的列

问题描述 投票:0回答:0

所以我正在使用 csv helper 30.0.1 并且我正在尝试阅读以下 cvs(缩短,原始文件更大但仍然有问题):

Report Status,Transaction Reference Number,Up-Front Payment,Up-Front Payment Currency
XXX,1111,,
XXX,1111,,
XXX,1111,,

但我得到了这个结果

CsvHelper.HeaderValidationException
  HResult=0x80131500
  Message=Header with name 'ReportStatus'[0] was not found.
Header with name 'TransactionReferenceNumber'[0] was not found.
Header with name 'UpfrontPayment'[0] was not found.
Header with name 'UpfrontPaymentCurrency'[0] was not found.
Headers: 'Report Status', 'Transaction Reference Number', 'Up-Front Payment', 'Up-Front Payment Currency'
Headers: 'Report Status', 'Transaction Reference Number', 'Up-Front Payment', 'Up-Front Payment Currency'
Headers: 'Report Status', 'Transaction Reference Number', 'Up-Front Payment', 'Up-Front Payment Currency'
Headers: 'Report Status', 'Transaction Reference Number', 'Up-Front Payment', 'Up-Front Payment Currency'
If you are expecting some headers to be missing and want to ignore this validation, set the configuration HeaderValidated to null. You can also change the functionality to do something else, like logging the issue.

IReader state:
   ColumnCount: 0
   CurrentIndex: -1
   HeaderRecord:
["Report Status","Transaction Reference Number","Up-Front Payment","Up-Front Payment Currency"]
IParser state:
   ByteCount: 0
   CharCount: 87
   Row: 1
   RawRow: 1
   Count: 4
   RawRecord:
Report Status,Transaction Reference Number,Up-Front Payment,Up-Front Payment Currency

我创建了以下类和方法来读取 csv。通过阅读几个示例,我找到了 PrepareHeaderForMatch 配置,因此我可以通过删除空格和破折号来匹配字段。但我仍然在创立这个问题。

public class MyClass
    {
        public string? ReportStatus { get; set; }
        public int? TransactionReferenceNumber { get; set; }
        public string? UpfrontPayment { get; set; }
        public string? UpfrontPaymentCurrency{ get; set; }
    }
public List<T> ReadFile<T>(string filePath)
        {
            var streamReader = new StreamReader(File.OpenRead(filePath));

            var config = new CsvConfiguration(CultureInfo.InvariantCulture)
            {
                PrepareHeaderForMatch = header => Regex.Replace(header.Header, @"[\s-]+", string.Empty)
            };

            var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture);

            csvReader.Context.TypeConverterOptionsCache.GetOptions<int?>().NullValues.Add("NULL");
            csvReader.Context.TypeConverterOptionsCache.GetOptions<decimal?>().NullValues.Add("NULL");

            var records = csvReader.GetRecords<T>().ToList();
            streamReader.Close();
            return records;
        }

我不知道有什么问题,因为我正在关注其他关于 PrepareHeaderForMatch 以及 getting started 页面的正确回复 12。如果有人指出我还有什么地方可以看或可能有什么问题,我将不胜感激。 谢谢!

c# csvhelper
© www.soinside.com 2019 - 2024. All rights reserved.