You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CsvHelper遇Configuration找不到及动态读取重复键报错求助

使用CsvHelper解析CSV时的配置错误及解决方法

遇到的问题

  • 未添加配置时,抛出错误:

    ArgumentException: An element with the same key '' already exists in the ExpandoObject. (Parameter 'key')

  • 尝试添加以下配置代码后,出现新错误:
    var csvReaderConfig = new Configuration();
    csvReaderConfig.HasHeaderRecord = false;
    

    The type or namespace name 'Configuration' could not be found (are you missing a using directive or an assembly reference?)

错误原因

  1. 初始错误:CSV文件无表头记录,但CsvHelper默认HasHeaderRecord为true,会尝试将空字符串作为动态对象的键,而动态对象不允许重复空键,因此抛出异常。
  2. 配置代码错误:CsvHelper 20+版本中,Configuration类已更名为CsvConfiguration,且原代码创建配置后未关联到CsvReader实例,配置无法生效。

修正后的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;

namespace CsvHelperTest
{
    internal class CsvHelperTester
    {
        static void Main(string[] args)
        {
            // 创建Csv配置实例,关闭表头记录
            var config = new CsvConfiguration(CultureInfo.InvariantCulture)
            {
                HasHeaderRecord = false
            };

            using (var streamReader = new StreamReader(@"C:\Users\eyoung\Desktop\parse test files\SWR-150106-1_AN00045613_20150415_XF28572.csv"))
            {
                // 实例化CsvReader时传入配置
                using (var csvReader = new CsvReader(streamReader, config))
                {
                    var records = csvReader.GetRecords<dynamic>().ToList();
                }
            }
        }
    }
}

关键说明

  • 必须引用CsvHelper.Configuration命名空间,才能使用CsvConfiguration类。
  • 需在实例化CsvReader时传入配置对象,确保配置被正确应用。
  • 设置HasHeaderRecord = false后,CsvHelper会将每行数据按索引(如0、1、2)映射为动态对象的键,避免空键重复问题。

内容的提问来源于stack exchange,提问作者Kevin Jablowski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:57:34