FileHelpers导入问题

时间:2013-10-11 15:00:02

标签: vb.net filehelpers

下午好,我一直在尝试从txt / csv文件导入一个字段,导致导入错误。我知道为什么我似乎无法弄清楚如何解决它。 我有一个下面列出的字符串,它在运行时导致错误。问题是事故描述被正确引用,但也包含另一组双引号。有什么方法可以从引用的字符串中删除引号吗?

"123456","I heard a "pop" in my shoulder","01/01/1900"

这是FileHelpers类

Namespace xxx
    <DelimitedRecord(","), IgnoreFirst(1)>
    Public Class  yyy 

        <FieldQuoted()> _
        Public IDAs String
        <FieldQuoted()> _
        Public AccidentDescr As String
        <FieldQuoted()> <FieldConverter(ConverterKind.Date, "yyyy-MM-dd")> _
        Public DOI As DateTime

任何帮助都会很棒

1 个答案:

答案 0 :(得分:0)

诀窍是不使用FieldQuoted属性,而是应用自定义FieldConverter来删除引号。

Public Class MyQuotedStringConverter
    Inherits ConverterBase
    Public Overrides Function StringToField(from As String) As Object
        ' StringToField() is used by import. The 'from' parameter will contain all the text between the comma delimiters (including all quotes)

        Dim result As String = from
        ' remove the first and last quotes
        If result IsNot Nothing Then
            If result.StartsWith("""") Then
                result = result.SubString(1)
            End If
            If result.EndsWith("""") Then
                result = result.SubString(0, result.Length - 1)
            End If
        End If
        Return result
    End Function

    Public Overrides Function FieldToString(fieldValue As Object) As String
        ' FieldToString is used by export
        Return fieldValue.ToString()
    End Function
End Class

并更改任何问题字段以使用转换器。例如

<DelimitedRecord(","), IgnoreFirst(1)>
Public Class  yyy 

    <FieldConverter(GetType(MyQuotedStringConverter))> _
    Public IDAs String
    <FieldConverter(GetType(MyQuotedStringConverter))> _
    Public AccidentDescr As String
    <FieldQuoted()> <FieldConverter(ConverterKind.Date, "yyyy-MM-dd")> _
    Public DOI As DateTime