1

如果有错误,我想输出当前行,但我收到一条消息,指出当前记录什么都没有。

这是我的代码:

Dim currentRow As String()
Using MyReader As New FileIO.TextFieldParser(filenametoimport)
  MyReader.TextFieldType = FileIO.FieldType.Delimited
  MyReader.SetDelimiters(",")

  While Not MyReader.EndOfData
    Try
      currentRow = MyReader.ReadFields()
      ImportLine(currentRow)
    Catch ex As FileIO.MalformedLineException
      report.AppendLine()
      report.AppendLine($"[{currentrow}]")
      report.AppendLine("- record is malformed and will be skipped. ")
      Continue While
    End Try
  End While
end Using

我需要输出当前行,以便向用户报告有不良记录。

report.AppendLine($"[{currentrow}]")

我知道如果解析失败,该值将为空,但有没有办法获取当前记录?

如果无法解析记录,如何输出该记录?

感谢您的帮助!

4

2 回答 2

0

我没有收到编译错误,MyReader.SetDelimiters(",")但无论如何我将其更改为数组。该report.AppendLine($"[{currentrow}]")行可能不需要数组。我改变了那条线以提供一个字符串。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim currentRow As String() = Nothing
    Using MyReader As New FileIO.TextFieldParser("filenametoimport")
        MyReader.TextFieldType = FileIO.FieldType.Delimited
        MyReader.SetDelimiters({","})

        While Not MyReader.EndOfData
            Try
                currentRow = MyReader.ReadFields()
                ImportLine(currentRow)
            Catch ex As FileIO.MalformedLineException
                report.AppendLine()
                report.AppendLine($"[{String.Join(",", currentRow)}]")
                report.AppendLine("- record is malformed and will be skipped. ")
                Continue While
            End Try
        End While
    End Using
End Sub

编辑

根据@ Joel Coehoorn 和@ ErocM 的评论,如果该行为空,您可以提供前一行的内容,以便可以找到错误的行。

        Dim LastGoodRow As String()
        While Not MyReader.EndOfData
            Try
                currentRow = MyReader.ReadFields()
                ImportLine(currentRow)
                LastGoodRow = currentRow
            Catch ex As FileIO.MalformedLineException
                report.AppendLine()
                report.AppendLine($"[{String.Join(",", LastGoodRow)}]")
                report.AppendLine("- record following this row is malformed and will be skipped. ")
                Continue While
            End Try
        End While
于 2019-08-20T19:01:52.857 回答
0

无法直接在异常中获取原始数据,但至少可以获取发生错误的行号。您可以使用该行号返回并找到违规记录:

Dim currentRow As String()
Using MyReader As New FileIO.TextFieldParser(filenametoimport)
  MyReader.TextFieldType = FileIO.FieldType.Delimited
  MyReader.SetDelimiters(",")

  While Not MyReader.EndOfData
    Try
      currentRow = MyReader.ReadFields()
      ImportLine(currentRow)
    Catch ex As FileIO.MalformedLineException
      report.AppendLine($"{vbCrLf}- record at line {ex.LineNumber} is malformed and will be skipped. ")
    End Try
  End While
End Using

TextFieldParser还提供对底层流的访问,并提供一种ReadLine()方法,因此如果您真的很想编写代码,您可以将流返回到上一行结尾,然后调用MyReader.ReadLine()以获取记录(这反过来会推进流再次到您期望的位置)。

于 2019-08-20T19:10:51.633 回答