Search code examples
text-files

Reading Specific Lines of Text from multiple Text Files


I am very new to vb and have been stepping my foot into the waters. I read a lot of posts on this site and it has helped me tremendously. Thanks all!

I have been searching to no end trying to figure out how to write the rest of this code. Basically, I have a directory with a lot of member text files in which stores data about each member. Each line of each member text file is the same criteria: Line1: FirstName, Line2: LastName, Line3: ExpDate, Line4: Status. I need a way to pull Line2 into Listbox1 and Line4 into Listbox2 from each text file. I have tried the following code and it partially seems to work but doesn't complete itself and gives an error.

Error: "Index was out of range. Must be a non-negative and less than the size of the collection. Parameter name: index"


Dim DirActiveMembers() As String = Directory.GetFiles("C:\SPCMembership\Active\")

For Each Member In DirActiveMembers

Dim Line2 As Integer = 2 'Last Name

Dim Line4 As Integer = 4 'Status

Dim LastName As String = (File.ReadAllLines(Member).ElementAt(Line2).ToString)

Dim Status As String = (File.ReadAllLines(Member).ElementAt(Line4).ToString)

ListBox1.Items.Add(LastName)

ListBox2.Items.Add(Status)

Next

Help! please and thank you for your time! :)


Solution

  • I dont have time to test out code at the moment but I was thinking something like this:

    Dim Line As String
    Dim fn as Integer
    
        For Each Member In DirActiveMembers
            fn = FreeFile()
            FileOpen(fn, Member, OpenMode.Input)
    
            line = LineInput(fn)
            line = LineInput(fn)
            Listbox1.Items.Add(line)
            line = LineInput(fn)
            line = LineInput(fn)
            Listbox2.Items.Add(line)
            FileClose(fn)
    
        Next
    

    Sorry for any formatting issues I'm on my phone

    Edit: So for a little explanation if I understood correctly you only need lines 2 and 4 so just read the first line and dont do anything with it. Read the second and add it to the 1st listbox, then read the 3rd (don't do anything with it) and then finally read the 4th line and add it to the 2nd listbox, then close the file