I'm updating some old code to use SortedList(Of String, Integer) objects and the lowest level function has all of a sudden begun throwing errors. The "KeyNotFoundException" error is thrown as I begin enumerating through the parsed line. Code as follows:
Public Function GetFileToolList(ByVal EIAFilePath As String) As SortedList(Of String, Integer)
'Gets a full list of tools being used (and reused) in a GCode program
Dim tools As New SortedList(Of String, Integer)
Dim words() As String
For Each line As String In IO.File.ReadAllLines(EIAFilePath)
'Determine if line contains M6
If line.ToUpper.Contains("T") Then
If line.Contains("M06") Or line.Contains("M6") Then
'If line ends with M06(M6) or contains M06(M6) then parse string to extract tool number
' If line contains M06(M6) then parse to second tool number after M-Code
' Example: T120 M06 T121
' Changes from T120 to T121
words = line.Split(" ")
If Not IsNothing(words) Then
'THE FOLLOWING LINE THROWS KeyNotFoundException
For i = 0 To words.Length - 1 Step 1
If words(i).ToUpper.StartsWith("T") Then
If Not (i + 1) >= words.Length Then
If words(i + 1).ToUpper.Contains("M06") Or words(i + 1).ToUpper.Contains("M6") Then
'START OF UPDATED CODE**********************
If IsNothing(tools) Then
tools.Add(words(i).Remove(0, 1), 1)
Else
If Not tools.ContainsKey(words(i).Remove(0,1)) Then
tools.Add(words(i).Remove(0, 1), 1)
Else
tools(words(i).Remove(0, 1)) += 1
End If
End If
'END OF UPDATED CODE************************
Continue For
End If
End If
End If
Next
End If
End If
End If
Next
Return tools
End Function
All of the threads I've seen with regard to this error regard Dictionary objects. The closest I have is the 'tools' SortedList object, but the exception is thrown on a String array. So, what might cause this exception and bonus points if you can explain why the exception occurs with the enumeration of the "words". Thanks in advance!