이 파일에는 유효하지 않은 CSV가 들어 있으며 일반적으로 구문 분석 할 수 없습니다. 그래서 "엉망"의 근원을 고쳐야합니다. Catch
에서
Function FixRowFieldsQuoteIssue(parser As TextFieldParser) As String()
If Not parser.HasFieldsEnclosedInQuotes Then Return Nothing 'method fixes quote issue
Dim errorLine As String = parser.ErrorLine
If String.IsNullOrWhiteSpace(errorLine) Then Return Nothing ' empty line no quote issue
errorLine = errorLine.Trim()
If Not errorLine.StartsWith("""") Then Return Nothing ' must start with quote otherwise fix not supported
Dim lineFields As New List(Of String)
Dim insideField As Boolean = False
Dim currentField As New List(Of Char)
For i As Int32 = 0 To errorLine.Length - 1
Dim c As Char = errorLine(i)
Dim isDelimiter = parser.Delimiters.Contains(c)
Dim isQuote = c = """"
If insideField Then
If isQuote Then
If i = errorLine.Length - 1 OrElse
parser.Delimiters.Contains(errorLine(i + 1)) Then
' delimiter follows, this is a valid end field quote
' can be improved by skipping spaces until delimiter
insideField = False
lineFields.Add(String.Concat(currentField))
currentField = New List(Of Char)
Else
' next char not a delimiter, this is invalid
' add this quote to regular field-chars to fix it
currentField.Add(c)
End If
Else
' regular char, add it to the current field chars
currentField.Add(c)
End If
ElseIf isQuote Then
insideField = True
End If
Next
Return lineFields.ToArray()
End Function
전화를 : 당신은 당신이 그것을 해결하기 위해 시도하는 방법 쓸 수 있다고 할 수없는 경우,
Dim allRowFields As New List(Of String())
Using parser As New FileIO.TextFieldParser("filePath")
parser.Delimiters = New String() {","}
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = False
While Not parser.EndOfData
Try
Dim currentRowFields As String() = parser.ReadFields()
allRowFields.Add(currentRowFields)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
Dim fixedFields As String() = FixRowFieldsQuoteIssue(parser)
If fixedFields IsNot Nothing Then
allRowFields.Add(fixedFields)
Else
MsgBox("Line " & ex.Message & "Is Not valid And will be skipped.")
End If
End Try
End While
End Using
파일을 큰 따옴표로 다시 써서'' "'로 쓸 수 있습니까? 큰 따옴표가있는 항목은 항상 줄의 마지막 항목입니까? 다른 필드에 쉼표가 있습니까? –
파일에 잘못된 csv가 있습니다. 그 난장판을 고칠 수 있니? 아니면 파싱해야합니까? –
구분 기호가 다른 '필드'에 나타나지 않는 세미콜론, 파이프 또는 다른 문자로 구성되도록 'CSV'파일을 변경할 수 있습니까 – Mych