As of now I am trying to read in a text file that is tab delimited with uneven columns. My problem is that when I try to split the file into respective lines, I get an "out of array bound" error. I know this is due to have a NULL value in certain row/columns places. Is there a way to just read through each row instead of relying on each column to have a value in it? I have attached my input file for easy viewing.

Here is my code thus far:

        Dim infile As IO.StreamReader = IO.File.OpenText("input.txt")
        Dim lines() As String
        Dim outFile As IO.StreamWriter = IO.File.CreateText("out.txt")

        Dim col1 As Char
        Dim col2 As String
        Dim col3 As String
        Dim col4 As String
        Dim col5 As String

        For Each line In IO.File.ReadAllLines("input.txt")

            lines = infile.ReadLine.Split(vbTab)

            col1 = lines(0)
            col2 = lines(1)
            col3 = lines(2)
            col4 = lines(3)
            col5 = lines(4)     'Error here

            With outFile
            End With

P	Joe Smith	123-4567	BCBS
P	Bollo Naboo	867-5309	APE
P	Howard Moon	123-1234	BCBS
P	Vince Noir	432-4321	BCBS
A	123-4567	A	D Stantz	45
A	123-4567	A	T M 12:00	30
A	123-4567	A	N	30
A	123-4567	D	M 12:00
4 Years
Discussion Span
Last Post by xcarbonx

You could try

For Each line As String In System.IO.File.ReadAllLines("d:\temp\test.txt")

    Dim col() As String = {"", "", "", "", ""}
    Dim fld() As String = line.Split(vbTab)

    For i As Integer = 0 To UBound(fld)
        col(i) = fld(i)

    For i As Integer = 0 To UBound(col)
        Debug.WriteLine(" field " & i & " = " & col(i))


Could also do something like this:

For Each line As String in System.IO.File.RealAllLines("input.txt")
    Dim lstData As New List of String
    lstData = line.Split(vbTab).ToList

    For i = 0 To lstData.Count - 1

Edited by Begginnerdev


I think the problem is that he wants to define a field value for each field (null if the field is not present). One obvious problem is what happens when it's not the last field that is missing.


Yes I would like each column assigned to a variable, because i plan to use a switch statement for some of them. Ex- Switch (col1) case "a" case "p". Is there a way to get around some records being null in certain columns? Is it possible just to read by row instead of column since there are uneven columns?


Is there a way to get around some records being null in certain columns?

As long as the fields (including missing ones) are delimited by tabs then my code will work.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.