简体   繁体   English

CsvHelper 从没有 Header 的文件中加载数据表不工作

[英]CsvHelper Load DataTable from File with No Header Not Working

I have some simple code that will load a DataTable from a.csv file if it includes a header.我有一些简单的代码,如果它包含 header 文件,它将从 a.csv 文件加载数据表。 Now I need to load a DataTable from a file without a header.现在我需要从没有 header 的文件中加载数据表。 I was expecting to set HasHeaderRecord = false and the DataTable would be created with default headers (Field1, Field2, ...).我期待设置 HasHeaderRecord = false 并且 DataTable 将使用默认标题(Field1,Field2,...)创建。 This is not the case, I can see the records are read by the CsvReader but since there are no headers there are no columns created in the DataTable.情况并非如此,我可以看到 CsvReader 读取了记录,但由于没有标题,因此 DataTable 中没有创建列。 It seems like this should be simple, what am I missing?看起来这应该很简单,我错过了什么? Also, this can't be hardcoded or loaded using a class map, since the files are dynamic.此外,由于文件是动态的,因此不能使用 class map 对其进行硬编码或加载。

var dt = new DataTable();

        var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            HasHeaderRecord = false
        };

        var enc = System.Text.ASCIIEncoding.UTF8;

        using (var reader = new StreamReader(FileName, enc, true))
        using (var csv = new CsvReader(reader, csvConfig))
        {
            // Do any configuration to `CsvReader` before creating CsvDataReader.
            using (var dr = new CsvDataReader(csv))
            {
                dt.Load(dr);
            }
        }

Seems to be a bug in the library as you can read here: https://github.com/JoshClose/CsvHelper/issues/1240似乎是库中的一个错误,您可以在此处阅读: https://github.com/JoshClose/CsvHelper/issues/1240

Since they haven't fixed it in the last 2 years, who knows if they will ever do.由于他们在过去 2 年没有修复它,谁知道他们是否会修复它。 Until then you can use this code which should work as expected:在此之前,您可以使用应该按预期工作的代码:

using (var reader = new StreamReader(FileName, enc, true))
using (var csv = new CsvReader(reader, csvConfig))
using (var dr = new CsvDataReader(csv))
{
    while (dr.Read())
    {
        if (dt.Columns.Count == 0)
        {
            for (int i = 0; i < dr.FieldCount; i++)
                dt.Columns.Add();
        }

        DataRow row = dt.NewRow();
        for (int i = 0; i < dr.FieldCount; i++)
            row[i] = dr.GetString(i);
        dt.Rows.Add(row);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM