csvhelper IsHeaderCaseSensitive Work around

本文关键字:around Work IsHeaderCaseSensitive csvhelper | 更新日期: 2023-09-27 18:10:17

我试图在一个标题为'EMAIL'的csv文件中读取,但是,我不断得到CsvMissingFieldException抛出"字段'EMAIL'不存在于csv文件"。

我设置CSVreader来处理-

csvReader.Configuration.IsHeaderCaseSensitive = false;

但我仍然得到同样的问题。有人知道变通的办法吗?或者为什么配置不起作用?

在我的Utilities类中:

public static IEnumerable<T> CSVreader<T>(string fileName)
        {
            using (var fileReader = File.OpenText(fileName))
            using (var csvReader = new CsvHelper.CsvReader(fileReader))
            { 
                csvReader.Configuration.IsHeaderCaseSensitive = false;
                csvReader.Configuration.RegisterClassMap<OptOutClassMap>();
                while (csvReader.Read())
                {
                    var record = csvReader.GetRecord<T>();
                    yield return record;
                }
            }
        }

在我的类映射类:

public string Email { get; set; }
public class CustomClassMap : CsvHelper.Configuration.CsvClassMap<CustomMap>
    {
        public override void CreateMap()
        {
            Map(m => m.Email);  
        }
    }

csvhelper IsHeaderCaseSensitive Work around

看起来您没有使用正确的ClassMap。从上面的代码中,行:

csvReader.Configuration.RegisterClassMap<OptOutClassMap>();
应:

csvReader.Configuration.RegisterClassMap<CustomClassMap>();

修改后的代码按预期工作。

static void Main(string[] args)
{
    var records = CSVreader<Record>("TextFile1.csv");            
}
public class Record
{
    public string Email { get; set; }
}
public class CustomClassMap : CsvHelper.Configuration.CsvClassMap<Record>
{
    public override void CreateMap()
    {
        Map(m => m.Email);
    }
}
public static IEnumerable<T> CSVreader<T>(string fileName)
{
    using (var fileReader = File.OpenText(fileName))
    using (var csvReader = new CsvHelper.CsvReader(fileReader))
    { 
        csvReader.Configuration.IsHeaderCaseSensitive = false;
        csvReader.Configuration.RegisterClassMap<CustomClassMap>();
        while (csvReader.Read())
        {
            var record = csvReader.GetRecord<T>();
            yield return record;
        }
    }
}