0

I want to read fixed length files.
I know how to do this if I know the field lengths.

 Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(filePath)

        Reader.TextFieldType =
        Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
        Reader.SetFieldWidths(8, 16, 16, 12, 14, 16) 'They are different in each file

        Dim currentRow As String()
        While Not Reader.EndOfData
            Try
                currentRow = Reader.ReadFields()
                Dim currentField As String
                For Each currentField In currentRow
                    MsgBox(currentField)
                Next
            Catch ex As Microsoft.VisualBasic.
                        FileIO.MalformedLineException
                MsgBox("Line " & ex.Message &
                "is not valid and will be skipped.")
            End Try
        End While
    End Using

The problem is that I don't know the length of each field.
Is there a way to read the first line and get the Field lengths?

Nianios
  • 1,391
  • 3
  • 20
  • 45

1 Answers1

0

Since I have found the answer, I'll post it here in case someone will face the same problem.
I solved it using regex

'sRowData is the first line of the file
 Dim pArLengths() As Integer = Nothing 'Array to store the lengths

 Dim regex As New Regex("[^\W_\d]+", _
                        RegexOptions.IgnoreCase _
                        Or RegexOptions.Multiline _
                        Or RegexOptions.Singleline _
                        Or RegexOptions.IgnorePatternWhitespace)

 Dim myMatches As MatchCollection = regex.Matches(sRowData)

 ReDim pArLengths(myMatches.Count - 1)

 For i = 0 To myMatches.Count - 1
     Dim k As Integer
     k = If(i < myMatches.Count - 1, myMatches(i + 1).Index, sRowData.Length)
     pArLengths(i) = k - myMatches(i).Index
 Next

I hope that someone will find it useful.

Nianios
  • 1,391
  • 3
  • 20
  • 45