2016-08-31 2 views
0

나는 코드 아래 사용하여 CSV 파일을 읽고 filehelper 유효성 검사를 호출하고Filehelper 각 행의 모든 ​​오류를 포착하지

[DelimitedRecord(",")] 
[IgnoreEmptyLines] 
public class CustomerClass 
{ 
    [FieldConverter(ConverterKind.Date, "MM/dd/yyyy")] 
    private DateTime EffectiveDate; 

    [FieldNotEmpty] 
    [FieldQuoted(QuoteMode.OptionalForRead)] 
    private string CustomerID; 
} 

다음과 같이 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에 잘못된 날짜 형식 (잘못된 날짜 형식)과 CustomerID (null 값 전달)가 모두 오류가있는 경우 각 행에 대해 첫 번째 오류 만 캡처됩니다.

모든 열에서 오류를 캡처하고 첫 번째 오류가 발생해도 멈추지 않으려면 어떻게해야합니까? 내가 Filehelper 3.1.5을 사용하고

감사합니다,

+1

라이브러리의 라인에 오류가 발견되면 그 라인의 나머지는 유효하지 않을 수 있기 때문에 구문 분석을 계속하지 않으므로 다음 라인으로갑니다, 미안 해요 – MarcosMeli

답변

0

난 당신이, 당신은 필드로 필드를 확인할 수 있습니다 CsvHelper를 사용하는 제안 : 코멘트에 언급 @MarcosMeli으로

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 
      } 
     } 
    } 
0

:

라이브러리가 라인에서 오류를 발견하면 나머지 라인이 유효하지 않을 수 있으므로 파싱을 계속하지 않음 XT 라인

당신이 정말로 모든 오류를보고해야하는 경우, 당신은 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); 
} 
관련 문제