我在类中有两个字段,由filehelper引擎使用,如下所示
[DelimitedRecord(",")]
[IgnoreEmptyLines]
public class CustomerClass
{
[FieldConverter(ConverterKind.Date, "MM/dd/yyyy")]
private DateTime EffectiveDate;
[FieldNotEmpty]
[FieldQuoted(QuoteMode.OptionalForRead)]
private string CustomerID;
}
我正在阅读csv文件并使用下面的代码
调用filehelper验证var engine = new DelimitedFileEngine<CustomerClass>;
engine.Options.IgnoreFirstLines = 1;
engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
List<CustomerClass> Result = engine.ReadFile(filepath).ToList();
ErrorInfo[] errorInfo = engine.ErrorManager.Errors;
如果我的csv在EffectiveDate(日期格式错误)和CustomerID(传递空值)中都有错误,则每行只捕获第一个错误。
如何捕获所有列中的错误,而不是在发生第一个错误时停止? 我正在使用Filehelper 3.1.5
谢谢,
答案 0 :(得分:0)
I would suggest you to use CsvHelper, you can verify field by field:
using (TextReader reader = File.OpenText("Pasta1.csv"))
{
var csv = new CsvReader(reader);
csv.Configuration.Delimiter = ",";
while (csv.Read())
{
CustomerClass record = new CustomerClass();
record.CustomerID = (string)csv.GetField(typeof(string), "CustomerID");
if (string.IsNullOrEmpty(record.CustomerID))
{
//CustomerID is null
}
if (!csv.TryGetField<DateTime>("EffectiveDate", out record.EffectiveDate))
{
//EffectiveDate incorrect
}
}
}
答案 1 :(得分:0)
正如@MarcosMeli在评论中提到的那样:
当库找到一行中的错误时,不会继续解析它 因为该行的其余部分可能无效,因此它会转到下一行 线
如果您确实需要报告所有错误,则需要使用AfterReadRecord
事件和
手工完成更多的处理。
首先,您需要将所有字段更改为string
,以便没有错误。
[DelimitedRecord(",")]
[IgnoreEmptyLines]
public class CustomerClass :
{
public string EffectiveDate;
[FieldQuoted(QuoteMode.OptionalForRead)]
public string CustomerID;
}
然后你需要添加一个事件并处理那里的所有验证。类似的东西:
void Engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<UserInfoFromAd> e)
{
string allMyErrors = null;
bool isDateValid = IsDateValid(e.Record.EffectiveDate);
if (!isDateValid)
{
allMyErrors += "Date is invalid. ";
}
bool isCustomerIdValid = IsCustomerIDValid(e.Record.CustomerID);
if (!isCustomerIdValid)
{
allMyErrors += "CustomerID is invalid. ";
}
if (!String.IsNullOrEmpty(allMyErrors))
throw new Exception(allMyErrors);
}