【问题标题】:Using ReadFields() function, retrieve n-th field value使用 ReadFields() 函数,检索第 n 个字段值
【发布时间】:2014-01-16 18:27:55
【问题描述】:

我目前正在阅读一个具有固定宽度的文本文件。除了循环,有没有办法让我们说第五个值(如果您查看 fixedWidths,这是一个字符)?

这是我的代码的副本:

Private Function processPaymentRow(currentLine As String)
  Dim result As String()

  Using strStream As New StringReader(currentLine)
    Using MyReader As New TextFieldParser(strStream)
      MyReader.TextFieldType = FieldType.FixedWidth
      'Set proper field widths for the payment row here
      MyReader.FieldWidths = {10, 1, 10, 8, 1, 20, 13, 1, 8, 8, 8, 40,
                              40, 40, 40, 40, 25, 2, 9, 40, 10, 20, 6}
      Try
        result = MyReader.ReadFields()
        'Dim currentField As String
      Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
        MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
      End Try
    End Using
  End Using
  For Each itm In result
    MsgBox(itm & " Pay")
    '// I can loop through the results and get the value I want.
  Next
  Return result
End Function

【问题讨论】:

  • 如果文件中有不止一行,你不需要循环吗?如果只有一行,则读取为文本并使用 substring(4,1) 读取第 5 个字符。
  • 我一次只阅读一行。如果我正在阅读整个文件,那么循环并获得我想要的值对我来说会更有意义。我有一个生成文本文件的系统,里面有很多无用的数据。我只需要提取我需要的值,这就是为什么我只想获得位置,而不是循环。不过还是谢谢。
  • 如果您一次只处理一个固定宽度的记录,为什么不直接使用 currentLine.substring(4,1)?
  • 文件中有两个不同的部分,具有不同的固定宽度和不同的字段。显示的付款和不显示的分配。如果始终都是相同的数据,那么使用 substring(4, 1) 将是一个很好的解决方案。

标签: vb.net parsing textfieldparser


【解决方案1】:

result 是一个字符串数组,所以你应该能够获取result(4),这应该会给你第五个值。

【讨论】:

  • 它有效。我想我之前尝试过但没有运行它,因为它说有可能出现空值......但是在查看我的代码之后,如果有空值,它就不会到达那一点。谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-03-29
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 2011-09-01
  • 1970-01-01
  • 2020-06-15
  • 2017-06-10
相关资源
最近更新 更多