Hing-Lun Ma Hing-Lun Ma - 4 months ago 39
C# Question

'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

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

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

while ((input = stream.ReadLine()) != null)
if (iCurRecLine == 0 && input.IndexOf(HeaderBeginKeyWord) >= 0)

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?


There seems to be no validation in the file content you're reading.

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


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

Could easily fail and throw this exception if the input only contains 10 characters.