"System.ArgumentOutOfRangeException" occurred in mscorlib.dll

Thank you in advance! I am writing an application to read a txt file and write to Excel. To start small, I'm just trying to read the first line.

Console.WriteLine correctly outputs the string (which has spaces between characters), but when I try to extract characters from the string, I get this error: Additional information: The index and length must refer to the location inside the string.

while ((input = stream.ReadLine()) != null) { //ACH HEADER LINE if (iCurRecLine == 0 && input.IndexOf(HeaderBeginKeyWord) >= 0) { Console.WriteLine(input); RepDate = input.Substring(23, 6).Trim(); RecordTypeCode = input.Substring(0, 1).Trim(); PriorityCode = input.Substring(1, 2).Trim(); ImmDestination = input.Substring(3, 10).Trim(); ImmOrigin = input.Substring(13, 10).Trim(); FileCreatedDate = input.Substring(23, 6).Trim(); FileCreatedTime = input.Substring(29, 4).Trim(); FileIDModifier = input.Substring(33, 1).Trim(); RecordSize = input.Substring(34, 3).Trim(); BlockingFactor = input.Substring(37, 2).Trim(); FormatCode = input.Substring(39, 1).Trim(); Destination = input.Substring(40, 23).Trim(); Origin = input.Substring(63, 23).Trim(); ReferenceCode = input.Substring(86, 8).Trim(); ... } } 

Where did I go wrong on this?

+4
source share
1 answer

There seems to be no check in the contents of the file you are reading.

.SubString() throws an ArgumentOutOfRangeException if startIndex plus length indicates a position not within this instance.

Thus:

  RepDate = input.Substring(23, 6).Trim(); 

It can easily compromise and throw this exception if input contains only 10 characters.

+6
source

Source: https://habr.com/ru/post/1501025/


All Articles