2017-05-16 15 views
0

FileHelpers를 읽는 방법 인용 된 필드에 작은 따옴표가 포함되어 있습니까? 인용 필드 상세하지만, 인용 문자를 "뿐만 아니라 분리하기 전에이다 -은 : 위의 레코드에 대한FileHelpers 인용 된 필드에 작은 따옴표가 포함되어 있습니까?

[DelimitedRecord(",")] 

public class LineModel 
{ 

[FieldQuoted('"', QuoteMode.OptionalForBoth)] 

public string Id; 

[FieldQuoted('"', QuoteMode.OptionalForBoth)] 

public string Details; 

[FieldQuoted('"', QuoteMode.OptionalForBoth)] 

public string Device; 

} 

얻기 오류 : 아래

내 CSV 기록

"1","7" Screen","Mobile" 

이 모델은 ([FieldTrim]을 사용하면이 오류를 피할 수 있습니다.)

답변

0

QuoteMode 모호한 인용문이있을 때 잘 작동하지 않습니다. 당신의 입력 파일에. 대신 [FieldQuoted] 특성을 제거하고 사용자 지정 변환기에서 따옴표를 처리 할 수 ​​있습니다.

[DelimitedRecord(",")] 
public class LineModel 
{ 
    [FieldConverter(typeof(MyQuotedFieldConverter))] 
    public string Id; 

    [FieldConverter(typeof(MyQuotedFieldConverter))] 
    public string Details; 

    [FieldConverter(typeof(MyQuotedFieldConverter))] 
    public string Device; 
} 

public class MyQuotedFieldConverter : ConverterBase 
{ 
    public override object StringToField(string from) 
    { 
     // If the field starts and ends with a double quote 
     if (from.StartsWith("\"") && from.EndsWith("\"")) 
     { 
      // Remove the first and last character 
      return from.Substring(1, from.Length - 1); 
     } 
     return from; 
    } 
} 

물론 필드 내에 ","가 있으면 문제가 발생합니다.

"1","7, Screen","Mobile" 

는 경우에, 당신은 INotifyRead 인터페이스를 구현하여 입력을 정리 레코드 라인을 사전에 분석해야합니다. 같은 뭔가 :

[DelimitedRecord(",")] 
public class LineModel : INotifyRead 
{ 
    //... fields as before 

    public void BeforeRead(BeforeReadEventArgs e) 
    { 
     if (e.RecordLine.Count(x => x == ',') > 3) 
     { 
      e.RecordLine = DetectAndReplaceEmbeddedDelimiters(e.RecordLine); 
     } 
    } 

    public void AfterRead(AfterReadEventArgs e) 
    {     
    } 
} 

또 다른 방법은 반대를 고려 : 임베디드 따옴표를 모든 분야에 따옴표를 추가하고 제거/교체를 위해 사용자 정의 컨버터를 사용합니다. 그런 다음 QuoteMode.AlwaysQuoted을 사용하십시오.