CsvHelper抛出CsvMissingFieldException异常
本文关键字:异常 CsvMissingFieldException 抛出 CsvHelper | 更新日期: 2023-09-27 18:10:01
我一直在尝试解析CSV文件:
NOTE: All directories are updated daily using information from the previous business day.
Company Name,Stock Symbol,DPM,Cycle,Traded at C2,LEAPS 2014,LEAPS 2015,LEAPS 2016,Product Types
(NEW) NEWS CORPORATION CLASS A,NWSA,SIG:MU,1,,,,Y,L,
1ST UNITED BANCORP INC (FL),FUBC,WOLVERINE,3,,,,,
21VIANET GROUP INC.,VNET,CITADEL,3,,,,,
22ND CENTURY GROUP INC.,XXII,CITADEL,1,,,,,
3-D SYSTEMS CORP,DDD,SIG,2,,,,Y,L,W,
3M COMPANY,MMM,SIG:MMM,1,Y,,,Y,L,W,
51JOB INC,JOBS,SIG,1,,,,,
58.COM INC.,WUBA,CITADEL,1,,,,,
8X8 INC-NEW,EGHT,SIG,2,,,,,
A A R CORP,AIR,CITADEL,2,,,,,
A V HOMES INC,AVHI,WOLVERINE,3,,,,,
A.M. CASTLE & CO,CAS,CITADEL,3,,,,,
A10 NETWORKS INC.,ATEN,CITADEL,3,,,,,
AARON''S INC,AAN,CITADEL,2,,,,,
使用以下代码(我使用子字符串来去掉NOTE部分):
void sciagnijSymbole_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String dane = e.Result.Substring(91);
using (TextReader sr = new StringReader(dane))
{
var csv = new CsvReader(sr);
csv.Configuration.RegisterClassMap<SymbolMap>();
var listaSymboli = csv.GetRecords<Symbol>().ToList();
}
}
public class Symbol
{
public String nazwa { get; set; }
public String symbol { get; set; }
}
public sealed class SymbolMap : CsvClassMap<Symbol>
{
public SymbolMap()
{
Map(m => m.nazwa);
Map(m => m.symbol);
}
}
它抛出一个CsvMissingFieldException消息:"字段'nazwa'不存在于CSV文件。"我不知道怎么了。我只希望第一列和第二列写入类,所以我做了一个映射,但它说字段不存在。另外,我从互联网上得到的CSV文件,所以我不想改变它。
如果您的属性名与csv文件中的列名不匹配,那么您必须在Map中指出列名:
public sealed class SymbolMap : CsvClassMap<Symbol>
{
public SymbolMap()
{
Map(m => m.nazwa).Name("Company Name");
Map(m => m.symbol).Name("Stock Symbol");
}
}