【发布时间】: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