Hello,

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
                .WriteLine(col1)
                .WriteLine(col2)
                .WriteLine(col3)
                .WriteLine(col4)
                .WriteLine(col5)
            End With

        Next

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)
    Next

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

Next

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
        outFile.WriteLine(lstData(i))
    Next
Next

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.

Thanks for your help Jim!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.