【发布时间】:2019-10-11 19:04:17
【问题描述】:
我正在尝试将 csv 文件解析为给定类的项目列表。我对 dotnet 世界很陌生。我正在使用 .NET (2.2.402) 这是我班级的代码
public class ItemResource
{
public string Msisdn { get; set; }
public float Amount { get; set; }
public string PersonName { get; set; }
public string Message { get; set; }
public string Description { get; set; }
/// <summary>
/// Tells wether or not the customer will receive a notification
/// </summary>
///
public int Notify { get; set; }
}
这是我尝试解析文件的代码部分
StreamReader reader = new StreamReader("path-to-file.csv");
var csvReader = new CsvReader(reader);
//csvReader.Configuration.Delimiter = ";";
//csvReader.Configuration.HeaderValidated = null;
var records = csvReader.GetRecords<ItemResource>();
_logger.LogInformation(records.Count().ToString());
foreach(var record in records)
{
_logger.LogInformation(record.ToString());
}
这是文件的内容
Msisdn, Amount, PersonName, Message, Description, Notify
69947943,150,Name 1,TEST,Test,1
69947943,150,Name 2,TEST,Test,1
69947943,150,Name 3,TEST,Test,1
69947943,150,Name 4,TEST,Test,1
69947943,150,Name 4,TEST,Test,1
69947943,150,Name 5,TEST,Test,1
正如您所看到的,为了测试,我对路径进行了编码。这是我遇到的错误
CsvHelper.HeaderValidationException:名称为“Msisdn”的标头不是 成立。如果您期望某些标题丢失并且想要 忽略此验证,将配置 HeaderValidated 设置为 null。 您还可以更改功能以执行其他操作,例如 记录问题。在 CsvHelper.Configuration.ConfigurationFunctions.HeaderValidated(布尔 isValid, String[] headerNames, Int32 headerNameIndex, ReadingContext 上下文)在 CsvHelper.CsvReader.ValidateHeader(ClassMap map) 在 CsvHelper.CsvReader.GetRecordsT+MoveNext() 在 System.Linq.Enumerable.Count[TSource](IEnumerable`1 源)在 OMBulkPayment.Controllers.PaymentsController.Payment(SavePaymentResource 资源)在 C:\Users\BMHB8456\source\repos\OMBulkPayment\OMBulkPayment\Controllers\PaymentsController.cs:line 59 at lambda_method(Closure, Object, Object[]) at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(对象 目标,对象 [] 参数)在 Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor 执行器,对象控制器,Object[] 论据)
【问题讨论】:
-
它在第一行的第一个字段上失败。这有时表明存在更大的问题,例如该文件实际上是空白的,包含无效字符,甚至顶部只有一个空行。检查文件。
-
我在 Windows 10 操作系统上工作,切换到 Macos High Sierra 后,我得到了确切的错误