Home > Net >  startIndex cannot be larger than length of string vb.net
startIndex cannot be larger than length of string vb.net

Time:06-22

I get the error "startIndex cannot be larger than length of string. Parameter name: startIndex" when I run the following code. The error occurs on this line and I think it is to do with the line.substring. The code runs smoothly when I take out line.Substring(11, 2) = "24" and run the code as If line.StartsWith("123") Then currentRecord.ID = line.

I can't seem to get rid of the error.

Dim lines = File.ReadLines(filePath)
If (line.StartsWith("123") And line.Substring(11, 2) = "24") Then currentRecord.ID = line

CodePudding user response:

You need to check the line is long enough to access the substring at that position and length. AndAlso conditions will only trigger if the previous condition = true. If your version of VB.NET doesn't support AndAlso you will need to use nested ifs.

Dim lines = File.ReadLines(filePath)
If (line.StartsWith("123") AndAlso Len(line)>=14 AndAlso line.Substring(11, 2) = "24") Then currentRecord.ID = line
  • Related