CSV Helper 说项目不存在

CSV Helper saying item does not exist when it does

我正在尝试使用 csv 帮助程序库来解析我的 csv。但是我有一个问题,它说文件中的项目代码不存在。

    // Adding stock item code 
Sage.Accounting.Stock.StockItem stockItem = new Sage.Accounting.Stock.StockItem();

string line = null;
public void ImportCsv(string filename)
{
         TextReader reader = File.OpenText(filename);



    var csv = new CsvReader(reader);
        csv.Configuration.HasHeaderRecord = true;
        csv.Read();
        // Dynamic
      // Using anonymous type for the class definition
        var anonymousTypeDefinition = new
        {
            Itemcode = string.Empty,
            Barcode = string.Empty 
        };
        var records = csv.GetRecords(anonymousTypeDefinition);


 }

这是csv结构

"Itemcode","Barcode","description"

"P4S100001","303300054486","Test Product"

这是我第一次使用 https://joshclose.github.io/CsvHelper/

中显示的 csvhelper

您的 GetRecords 函数需要像这样的类型说明符:

var records = csv.GetRecords<type>();

此外,您可能希望根据需要将 csv.Read() 放入 while 循环中。

由于您的所有值都有引号,因此您需要在配置中指定它。在 csvHelper 中使用引号令人沮丧。如果不是全部,如果值有引号,也有办法处理它,但不如这个好

 var csv = new CsvReader(reader,new CsvHelper.Configuration.Configuration
            {
                HasHeaderRecord = true,
                QuoteAllFields = true
            });


            var anonymousTypeDefinition = new
            {
                Itemcode = string.Empty,
                Barcode = string.Empty
            };
            var records = csv.GetRecords(anonymousTypeDefinition);

如果数据尚不存在,您最好创建一个强类型模型来保存数据

public class Item {
    public string Itemcode { get; set; }
    public string Barcode { get; set; }
    public string description { get; set; }
}

并使用GetRecords<T>()按类型读取记录

TextReader reader = File.OpenText(filename);
var csv = new CsvReader(reader);
var records = csv.GetRecords<Item>();