I'm not really sure how to word it, if it is possible, but part of my program reads from a text file. It then pulls out the necessary information needed from that file by finding key identifiers. Right now the code is written to find the first key identifier and then read each line after that, locating each subsequent identifier and pulling the data from it. In a few cases, the format examples I've worked with are a bit different which results in a runtime error. How can I tell the program to essentially skip that part of the text file if it's not reading it right and continue moving on? Here is somewhat of an example of the text file.

DID/"DATA EXTRACTED HERE"
NAM/"DATA EXTRACTED HERE"
STR/"DATA EXTRACTED HERE"
CTY/"DATA EXTRACTED HERE"

Sometimes there is an extra space in between each line or in a few cases, the line below is not even there. For the ones with spaces, I added a do loop to keep looking for that line and have had no problems, but I would rather the information for that individual item not be pulled from the text file while still reading the rest of it.

You can use a Try/Catch block.The exact form will depend on the error you are getting. The syntax is

Try
    'your code here to process the text
Catch ex As YourParticularException
    'this code executes when you get an error
End Try

'a general catch-all (which is not recommended) is

Try
    'your code here to process the text
Catch ex As Exception
    'this code executes when you get an error
End Try
Member Avatar for Unhnd_Exception

I think this is what you want. Its lengthy but more comments than code.

Heres an example file.

DID/"1"
 NAM/"DATA EXTRACTED HERE"
 STR/"DATA EXTRACTED HERE"
 CTY/"DATA EXTRACTED HERE"

 DID/"2"
 NAM/"DATA EXTRACTED HERE"



 STR/"DATA EXTRACTED HERE"
 CTY/"DATA EXTRACTED HERE"

 DID/"3"
 NAM/"DATA EXTRACTED HERE"


 STR/"DATA EXTRACTED HERE"
 CTY/"DATA EXTRACTED HERE"


 DID/"Will Not Be Added"
 NAM/
 CTY/"DATA EXTRACTED HERE"

 DID/"4"
 NAM/"DATA EXTRACTED HERE"
 STR/"DATA EXTRACTED HERE"
 CTY/"DATA EXTRACTED HERE"

There are 5 Packets there. 1 of them doesn't contain the correct info and will not be extracted. Everything else will.

Place all this code into a Form1 code file

Option Compare Text
'Option Compare will remove case sensitivity
'while comparing strings.
'With this on jj = JJ = True.

Public Class Form1

    'First off. I created a class 
    'to work with data.
    'No idea what you are doing so i made
    'a generic class named packet.

    'This class will store packet data
    'and will also help while iterating
    'the text file.

    Public Class Packet
        'Packet variables.

        'I would make all these private 
        'and use properties like Id is.
        'Omitted for brevity.
        Private fpId As String
        Public Name As String
        Public Street As String
        Public City As String

        'The total items per line in the file
        Public Const PacketSegments As Integer = 2

        'The key identifiers that make up a packet
        Protected Class Identifiers
            Public Const Id As String = "DID"
            Public Const Name As String = "NAM"
            Public Const Street As String = "STR"
            Public Const City As String = "CTY"
        End Class

        ReadOnly Property Id() As String
            Get
                Return fpId
            End Get
        End Property

        Sub New(ByVal id As String)
            If id Is Nothing Then id = String.Empty
            fpId = id
        End Sub

        'A function to work across all packets.
        'If the key passed in is DID then its the
        'primary id.
        Shared Function IsId(ByVal key As String) As Boolean
            If Not String.IsNullOrEmpty(key) Then
                Return CBool(key.Trim = Identifiers.Id)
            End If
        End Function

        'A function to work across all packets.
        'Returns true if all packet fields have been
        'entered.
        Shared Function IsComplete(ByVal item As Packet) As Boolean
            If item IsNot Nothing Then
                Return CBool(Not String.IsNullOrEmpty(item.Name)) AndAlso _
                       CBool(Not String.IsNullOrEmpty(item.Street)) AndAlso _
                       CBool(Not String.IsNullOrEmpty(item.City))
            End If
        End Function

        'Takes a key and value pair.  If the key is one
        'of the Packet.Identifiers then the value is added
        'to the appropriate field.
        Public Sub AddItem(ByVal key As String, ByVal value As String)
            If Not String.IsNullOrEmpty(key) AndAlso Not String.IsNullOrEmpty(value) Then
                Select Case key.Trim
                    Case Identifiers.Name
                        Name = value
                    Case Identifiers.Street
                        Street = value
                    Case Identifiers.City
                        City = value
                End Select
            End If
        End Sub

    End Class

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim StreamReader As IO.StreamReader = Nothing

        Dim WorkingPacket As Packet = Nothing
        Dim PacketList As New List(Of Packet)

        Dim Line As String()
        Dim Seperator As Char() = {"/"c}


        Try
            'Open the file of your choice.
            'Notice the finally block of this Try Catch Finally 
            'The StreamReader will be disposed no matter if there
            'is an error or not.  Disposing the StreamReader will
            'also dispose the FileStream so there is no need to 
            'create an actual variable to store the file.  That is why
            'I passed the FileStream straight into the Reader.
            'If you need to access the FileStream then use
            'StreamReader.BaseStream
            StreamReader = New IO.StreamReader(New IO.FileStream("TextFile1.txt", IO.FileMode.Open))


            'Read until we can't read no more.
            Do While StreamReader.EndOfStream = False

                'With the packet class set up this is going to be 
                'very simple.

                'Read a line, split it with the seperator, and stick it
                'in the Line variable.  Notice the RemoveEmptyEntries.
                'That will cause the Line Array to never have an empty
                'string in it.
                Line = StreamReader.ReadLine().Split(Seperator, StringSplitOptions.RemoveEmptyEntries)

                'Does this line have the correct number of parts?
                If Line.GetLength(0) = Packet.PacketSegments Then

                    'The Line has the correct number of parts.

                    'Does this line contain the primary id?
                    If Packet.IsId(Line(0)) Then
                        'This line is the primary id. We are ready
                        'to create a new packet and start extracting
                        'it's remaining data.

                        'Before we do that.
                        'Have we already started a packet and
                        'is it fully loaded?
                        If Packet.IsComplete(WorkingPacket) Then
                            'We have already started and its done.
                            'Add this fully loaded packet to the list.
                            PacketList.Add(WorkingPacket)
                        End If

                        'This is the primary key.  Create a new
                        'packet and keep reading. 
                        WorkingPacket = New Packet(Line(1))

                    ElseIf WorkingPacket IsNot Nothing Then
                        'This line is not the primary id but 
                        'we do have a packet were working on
                        'because itsNot nothing.

                        'Maybe its the rest of the packet.
                        'Send it to the packet and let it decide.
                        WorkingPacket.AddItem(Line(0), Line(1))

                    End If

                End If
            Loop

            'The file has been fully read at this point.
            'If the last packet in the file was read correctly
            'then it would not have been added to the list
            'in the loop.
            'Do we have a packet? Is it complete?
            If Packet.IsComplete(WorkingPacket) Then
                'We have one and its complete.
                'The last packet in the file was
                'in the correct format.
                PacketList.Add(WorkingPacket)
            End If

        Catch ex As Exception
            'An exception will be caught if there was a problem
            'with the file stream.
            'Our code causes no exeception.
        Finally
            'All done. No matter if there was an execption or not
            'Dispose the streamReader which will in turn dispose 
            'the file stream.
            If StreamReader IsNot Nothing Then StreamReader.Dispose()
        End Try

        'Just to see it
        For Each Pkt In PacketList
            MsgBox(Pkt.Id & vbCrLf & _
                   Pkt.Name & vbCrLf & _
                   Pkt.Street & vbCrLf & _
                   Pkt.City)
        Next

    End Sub
End Class

Thanks unhnd exception, that looks like what I am trying for. I have placed try catch blocks, but i think since i only have a couple placed in the code and more near the end, if an error occurs and it's caught, i still get a 'bad file name or number' runtime error. this box pops up repeatedly until the program is completely closed out. What I'm trying to do is pull information on a person from a text file which is compiled by another program. It's sort of a junk file as everything done with that program is spit out into this text file. Here is a code snippet of what I am doing right now.

  Sub IMPORT_LOGFILE(ByVal FILENAME As String)

        Dim myreader As StreamReader
        Dim currentrow As DataRow = filedata_person.NewRow
        Dim currentrow2 As DataRow = filedata_vehicle.NewRow
        Dim line_text As String = ""
        Dim counter As Integer = 1

        Dim state_start, zip_start, race_start, dob_start, height_start, weight_start, hair_start As Integer
        Dim eye_start, donor_start, DL_EXPIRE As Integer

        Dim PLT_NBR_START, PLT_TYP_START, PLT_DIVIDER, PLT_YEAR_START, PLT_MAKE_START, PLT_MODEL_START, PLT_STYLE_START As Integer
        Dim PLT_COLORP_START, PLT_EXPIRES_START As Integer

        filedata_person.Clear()
        filedata_vehicle.Clear()

        Try

            Write_Log_File("STARTING LOG FILE LOOKUP.", LOGFILENAME)

            myreader = IO.File.OpenText(FILENAME)

            While myreader.Peek() <> -1

                currentrow = filedata_person.NewRow
                currentrow2 = filedata_vehicle.NewRow

                line_text = myreader.ReadLine()

                If line_text.Length > 3 Then

                    If line_text.Substring(0, 3).ToString = "DID" Then
                        currentrow.Item("DID") = Trim(line_text.Substring(4, line_text.Length - 4))
                        line_text = myreader.ReadLine()



                        If line_text.Substring(0, 3).ToString = "NAM" Then
                            currentrow.Item("NAME") = Trim(line_text.Substring(4, line_text.Length - 4))
                        End If
                        line_text = myreader.ReadLine()
                        If line_text.Substring(0, 3).ToString = "STR" Then
                            currentrow.Item("STREET") = Trim(line_text.Substring(4, line_text.Length - 4))
                        End If
                        line_text = myreader.ReadLine()
                        If line_text.Substring(0, 3).ToString = "CTY" Then
                            state_start = line_text.IndexOf("ST/")
                            zip_start = line_text.IndexOf("ZIP/")
                            currentrow.Item("CITY") = Trim(line_text.Substring(4, state_start - 4))
                            currentrow.Item("STATE") = Trim(line_text.Substring(state_start + 3, 2))
                            currentrow.Item("ZIP") = Trim(line_text.Substring(zip_start + 4, 5))
                        End If
                        line_text = myreader.ReadLine()
                        If line_text.Substring(0, 3).ToString = "SEX" Then
                            race_start = line_text.IndexOf("RAC/")
                            dob_start = line_text.IndexOf("DOB/")
                            height_start = line_text.IndexOf("HGT/")
                            weight_start = line_text.IndexOf("WGT/")
                            hair_start = line_text.IndexOf("HAI/")
                            eye_start = line_text.IndexOf("EYE/")
                            donor_start = line_text.IndexOf("DONR/")

                            currentrow.Item("SEX") = Trim(line_text.Substring(4, 1))
                            currentrow.Item("RACE") = Trim(line_text.Substring(10, (dob_start - race_start) - 4))
                            currentrow.Item("DOB") = Trim(line_text.Substring(dob_start + 4, 6))
                            currentrow.Item("HGT") = Trim(line_text.Substring(height_start + 4, 3))
                            currentrow.Item("WGT") = Trim(line_text.Substring(weight_start + 4, 3))
                            currentrow.Item("HAIR") = Trim(line_text.Substring(hair_start + 4, 4))
                            currentrow.Item("EYE") = Trim(line_text.Substring(eye_start + 4, 4))

                            line_text = myreader.ReadLine()
                            If line_text.Substring(0, 2).ToString = "LT" Then
                                If line_text.Substring(4, 3).ToString <> "NON" Then
                                    DL_EXPIRE = line_text.IndexOf("EXP=")
                                    currentrow.Item("DLEXPIRE") = Trim(line_text.Substring(DL_EXPIRE + 4, 11))
                                End If
                            End If


                        End If
                        filedata_person.Rows.Add(currentrow)
Here's an example of what I am trying to read from the text file. Sometimes the DID is not directly above the NAM entry and other times the EXP date is not there, so when the program tries to trim out that data and it's not there, I get an error.

DID/X520-5209-0724-09
NAM/DOE, JOHN H                                                
STR/MY ADDRESS                                                
CTY/MY CITY         ST/AK ZIP/55555 CT/MY COUNTY           
SEX/M RAC/WHITE  DOB/062490 HGT/510 WGT/180 HAI/BLCK EYE/BRWN DONR/ N
LT= RGLR                      ISS= 04/19/2010 EXP= 06/24/2018 AT= ORG

Your format is very haphazard and difficult to parse. some parameters are designated as

NAME/VALUE

while others are

NAME=VALUE

Some lines contain one name/value pair and others contain multiple. Some values contain leading blanks (are they supposed to be removed or are they significant) and others do not. Some values contain embedded blanks (MY CITY) which makes it difficult to determine where the value ends.

Can the parameters be in any order? If so, how do you determine where one set of parameters ends and the next set begins? Does a text file contain more than one set of parameters?

Does the "=" character appear as anything other than a name/value separator? If not then the first thing I would do on input is replace "=" with "/". In any case, can you please provide feedback on the above questions?

Start with a new project. Add one button named btnTest. Add a multiling textbox name txtResults. Enable both scrollbars. My example reads the given data from the file d:\temp\testdata.txt. Change this as appropriate for your system.

This code parses only one block of the sample data. It is up to you to determine where one block ends and another begins. To handle blocks that are incomplete I suggest creating a Class which has one property for each parameter. The "New" method can initialize the fields to a default value.

As mentioned in the comments, by parsing from right to left we can easily handle the free (non-column specific) format. For example, using "^" to mark the end of line, by moving "^" after each parse and knowing the start and length of each NAME portion (the regular expression code calculates all that for you)

CTY/MY CITY       ST/AK ZIP/55555 CT/MY COUNTY
                                             ^

CTY/MY CITY       ST/AK ZIP/55555 CT/MY COUNTY
                                 ^

CTY/MY CITY       ST/AK ZIP/55555 CT/MY COUNTY
                       ^

CTY/MY CITY       ST/AK ZIP/55555 CT/MY COUNTY
                 ^





Imports System.Text.RegularExpressions

' This piece of code parses NAME/VALUE pairs in a block of text similar to
'
'   DID/X520-5209-0724-09
'   NAM/DOE, JOHN H
'   STR/MY ADDRESS
'   CTY/MY CITY       ST/AK ZIP/55555 CT/MY COUNTY
'   SEX/M RAC/WHITE  DOB/062490 HGT/510 WGT/180 HAI/BLCK EYE/BRWN DONR/ N
'   LT= RGLR               ISS= 04/19/2010 EXP= 06/24/2018 AT= ORG
'
' The problems associated with parsing this format are
'
'   Incosistent separators. In some cases "/" separates the name from the value and in
'   other cases "=" is used. To handle this we translate all "=" to "/" before parsing.
'
'   There may be multiple NAME/VALUE pairs per line. To handle this we use a regular
'   expression to determine the start position of each NAME. By parsing from right to
'   left we can pretend (for the next pair) that the line ends just to the left of the
'   previously parsed pair. As long as we Trim the tokens we can safely ignore the
'   trailing and leading blanks.

Public Class Form1

    Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click

        'this expression will match any sequence of upper case letters followed by a "/"

        Dim rex As New Regex("[A-Z]+/")

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

            line = line.Replace("=", "/")                   'use consistent separators          
            txtResults.AppendText(line & vbCrLf)            'display current line to parse      

            Dim ms As MatchCollection = rex.Matches(line)   'get start and length of all NAME/  
            Dim last As Integer = Len(line)                 'start at the end of the line       
            Dim pair(1) As String                           'to hold NAME/VALUE pairs           

            'process all NAME/VALUE pairs

            For i As Integer = ms.Count - 1 To 0 Step -1

                'get the next NAME/VALUE pair

                pair = line.Substring(ms(i).Index, last - ms(i).Index).Split("/")
                txtResults.AppendText("  " & Trim(pair(0)) & "=" & Trim(pair(1)) & vbCrLf)

                'update end of line marker to ignore what we just parsed

                last = ms(i).Index - 1

            Next

            txtResults.AppendText(vbCrLf)

        Next

    End Sub

End Class
Member Avatar for Unhnd_Exception

This will take care of you.

It will read your keys in any order. If one is not present it doesn't care. They can all be on one line or seperate lines. It doesn't care. The only thing that is requried is that a DID/ key is at the top of the packet. From that point on it will work itself out.

If you need to add more keys to search for all you need to do is add another constant in the Packet.Keys class.

Option Compare Text

Public Class Form1


        Public Class Packet

            Private PacketKeys As Dictionary(Of String, String)
            'Used to stores all the constants in a list
            Public Shared ReadOnly KeyBag As List(Of String)

            Sub New()
                PacketKeys = New Dictionary(Of String, String)
            End Sub

            Public Class Keys
                'Any key identifier that should be found
                'in the text file should be listed here.

                'If you need to add another one then simply
                'type in a new variable with the key and seperator.
                Public Const Id As String = "DID/"
                Public Const Name As String = "NAM/"
                Public Const Street As String = "STR/"
                Public Const City As String = "CTY/"
                Public Const State As String = "ST/"
                Public Const Zip As String = "ZIP/"
                Public Const County As String = "CT/"
                Public Const Sex As String = "SEX/"
                Public Const Race As String = "RAC/"
                Public Const DateOfBirth As String = "DOB/"
                Public Const Height As String = "HGT/"
                Public Const Weight As String = "WGT/"
                Public Const HairColor As String = "HAI/"
                Public Const EyeColor As String = "EYE/"
                Public Const Downer As String = "DONR/"
                Public Const LicenseType As String = "LT="
                Public Const IssueDate As String = "ISS="
                Public Const ExpirationDate As String = "EXP="
                Public Const What As String = "AT="
            End Class

            Public Sub SetValue(ByVal line As String)
                'Extracts key value pairs from a line.

                If Not String.IsNullOrEmpty(line) Then
                    Dim FirstIndex As Integer
                    Dim SecondIndex As Integer
                    Dim ExtractStartIndex As Integer

                    For i = 0 To KeyBag.Count - 1
                        'Search the line until a key is found.
                        FirstIndex = line.IndexOf(KeyBag(i))
                        SecondIndex = -1

                        If FirstIndex <> -1 Then

                            If Not PacketKeys.ContainsKey(KeyBag(i)) Then
                                'add this key to the packes keys if its not there
                                PacketKeys.Add(KeyBag(i), String.Empty)
                            End If

                            ExtractStartIndex = FirstIndex + KeyBag(i).Length

                            For j = i + 1 To KeyBag.Count - 1
                                'now search the line for another key.
                                SecondIndex = line.IndexOf(KeyBag(j))
                                If SecondIndex <> -1 Then
                                    'there is another key after the first key.
                                    'we need everything inbetween it for the value.
                                    PacketKeys(KeyBag(i)) = line.Substring(ExtractStartIndex, SecondIndex - (ExtractStartIndex)).Trim
                                    Exit For
                                End If
                            Next

                            If SecondIndex = -1 Then
                                'if the second index is -1 then the first key found was the
                                'last key on the line. We need everything to the right of the 
                                'first key for the value
                                If FirstIndex <> -1 AndAlso ExtractStartIndex <= line.Length Then
                                    PacketKeys(KeyBag(i)) = line.Substring(ExtractStartIndex).Trim
                                End If
                                Exit For
                            End If

                        End If

                    Next
                End If
            End Sub

            Public Function GetValue(ByVal key As String) As String
                If Not String.IsNullOrEmpty(key) Then
                    If PacketKeys.ContainsKey(key) Then
                        Return PacketKeys(key)
                    End If
                End If
                Return String.Empty
            End Function

            Shared Sub New()
                KeyBag = New List(Of String)
                'WTF
                Dim ConstantFields As Reflection.FieldInfo() = GetType(Keys).GetFields(Reflection.BindingFlags.Public Or Reflection.BindingFlags.Static)
                If ConstantFields IsNot Nothing Then
                    For Each Field In ConstantFields
                        KeyBag.Add(Field.GetValue(Field))
                    Next
                End If

                'The first time a packet is intialized this constructor will be run.
                'We have all the keys stored as constants in the Keys class.
                'We need them to be in a list or array so we can iterate through them.
                'One way to get them into a list is to add them 1 by 1.
                'This uses reflection to dynamically extract the contstant names and
                'values from the keys class an put them into the list.
                'Much easier.
            End Sub

            Shared Function IsId(ByVal line As String) As Boolean
                'if DID/ is on the line this this is the start of a packet.
                If Not String.IsNullOrEmpty(line) Then
                    Return CBool(line.IndexOf(Keys.Id) <> -1)
                End If
            End Function

        End Class

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

            Dim StreamReader As IO.StreamReader = Nothing
            Dim WorkingPacket As Packet = Nothing
            Dim PacketList As New List(Of Packet)
            Dim Line As String


            Try
                StreamReader = New IO.StreamReader(New IO.FileStream("TextFile1.txt", IO.FileMode.Open))

                Do While StreamReader.EndOfStream = False
                    Line = StreamReader.ReadLine()

                    If Packet.IsId(Line) Then

                        If WorkingPacket IsNot Nothing Then
                            PacketList.Add(WorkingPacket)
                            'Or
                            'MyTable.Rows.Add(GetRow(WorkingPacket,MyTable.NewRow())
                        End If

                        WorkingPacket = New Packet()
                        WorkingPacket.SetValue(Line)

                    ElseIf WorkingPacket IsNot Nothing Then
                        WorkingPacket.SetValue(Line)
                    End If

                Loop

                If WorkingPacket IsNot Nothing Then
                    PacketList.Add(WorkingPacket)
                    'Or
                    'MyTable.Rows.Add(GetRow(WorkingPacket,MyTable.NewRow())
                End If

            Catch ex As Exception
            Finally
                If StreamReader IsNot Nothing Then StreamReader.Dispose()
            End Try

            Dim Message As String
            For Each Pkt In PacketList
                Message = String.Empty
                For Each Key In Packet.KeyBag
                    Message &= Key & ":" & Pkt.GetValue(Key) & vbCrLf
                Next
                MsgBox(Message)
            Next
        End Sub

        Public Function GetRow(ByVal item As Packet, ByVal row As DataRow) As DataRow
            If item IsNot Nothing AndAlso row IsNot Nothing Then
                row("DID") = item.GetValue(Packet.Keys.Id)
                row("Name") = item.GetValue(Packet.Keys.Name)
                row("Street") = item.GetValue(Packet.Keys.Street)
                '...
                '...
                '...
            End If
            Return row
        End Function

    End Class
Member Avatar for Unhnd_Exception

I fudged up a little with the reading the keys in any order.

If you want to read the keys in any order then replace the SetValue sub to the one below.
After that you should have no problems when reading files like this.

DID/X520-5209-0724-09
NAM/DOE, JOHN HISS= 04/19/2010 EXP= 06/24/2018 AT=ORG                                                
STR/MY ADDRESSCTY/MY CITYST/AKZIP/55555CT/MY COUNTY           
SEX/M RAC/WHITEDOB/062490 HGT/510 WGT/180 HAI/BLCK EYE/BRWN DONR/ N
LT= RGLR                    


DID/X520-5209-0724-09NAM/DOE, JOHN H                                                
STR/MY ADDRESSCTY/MY CITY          
SEX/M RAC/WHITE EXP= 06/24/2018DOB/062490 HGT/510 WGT/180 HAI/BLCK EYE/BRWN DONR/ N
LT= RGLRAT= ORG

DID/X520-5209-0724-09
NAM/DOE, JOHN H                                                
ISS= 04/19/2010      LT= RGLRCTY/MY CITYSTR/MY ADDRESS      ZIP/55555 ST/AK
HGT/510 SEX/M RAC/WHITEDOB/062490  WGT/180 HAI/BLCK EYE/BRWN DONR/ N

The fixed SetValue sub

   Public Sub SetValue(ByVal line As String)

       If Not String.IsNullOrEmpty(line) Then
           Dim FirstIndex As Integer
           Dim SecondIndex As Integer
           Dim ExtractStartIndex As Integer
           Dim LowestSecondIndex As Integer

           For i = 0 To KeyBag.Count - 1
              'Search the line until a key is found.
              FirstIndex = line.IndexOf(KeyBag(i))
              SecondIndex = -1
              LowestSecondIndex = Integer.MaxValue

              If FirstIndex <> -1 Then

                 If Not PacketKeys.ContainsKey(KeyBag(i)) Then
                      'add this key to the packes keys if its not there
                       PacketKeys.Add(KeyBag(i), String.Empty)
                 End If

                 ExtractStartIndex = FirstIndex + KeyBag(i).Length

                 For j = 0 To KeyBag.Count - 1
                      If j = i Then Continue For
                       'now search the line for another key.
                       SecondIndex = line.IndexOf(KeyBag(j))

                      If SecondIndex > FirstIndex Then
                          'We need the second index to be the one thats
                          'closests to the right of the first index.
                          If SecondIndex < LowestSecondIndex Then
                              LowestSecondIndex = SecondIndex
                          End If
                      End If
                Next

                If LowestSecondIndex = Integer.MaxValue Then
                   'The second index was never found. We need everything to the right of the 
                   'first index for the value
                   If FirstIndex <> -1 AndAlso ExtractStartIndex < line.Length Then
                        PacketKeys(KeyBag(i)) = line.Substring(ExtractStartIndex).Trim
                   End If

                Else
                   'there is another key after the first key.
                  'we need everything inbetween the first and second index for the value.
                   PacketKeys(KeyBag(i)) = line.Substring(ExtractStartIndex, LowestSecondIndex - (ExtractStartIndex)).Trim
                 End If

          End If

        Next
       End If
    End Sub

@Unhnd Exception - I think a regular expression would eliminate a lot of the searching code

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.