【问题标题】:How to ignore separator definition while parsing a file?解析文件时如何忽略分隔符定义?
【发布时间】:2021-02-17 13:30:13
【问题描述】:

我正在使用 CsvHelper,但如果文件的第一行类似于 sep=,,我的解析就会崩溃

我是这样做的:

    using var reader = new StreamReader(fileStream);
    using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);

    return csv.GetRecords<ClassToReadInto>()
        .Select(t => new ClassToMapTo
        {
            // map goes here
        })
        .ToList();

会发生什么:

    CsvHelper.HeaderValidationException: Header with name 'Type'[0] was not found. // and a bunch of other names

所以 CsvHelper 只是试图将第一行视为标题行。我怀疑它甚至设置了这一行的分隔符。为了解决这个问题,我只想到了这样的东西:

    while (csv.Read())
    {
        csv.ReadHeader();

        try
        {
            csv.ValidateHeader(typeof(CsvOrder));
            break;
        }
        catch { }
    }

有没有“正确的方法”这样做?

【问题讨论】:

    标签: csv csvhelper


    【解决方案1】:

    如果它一直存在,你可以先读一行。

    csv.Read();
    var records = csv.GetRecords<ClassToReadInto>();
    

    如果它不总是存在,您需要进行检查。

    csv.Read();
    if (!csv[0].StartsWith("sep="))
    {
        // The first row is the header, so we need to read it.
        csv.ReadHeader();
    }
    var records = csv.GetRecords<ClassToReadInto>();
    

    【讨论】:

      猜你喜欢
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 2014-05-28
      • 2020-12-30
      • 2014-09-27
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多