'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Asked Answered
W

1

6

I'm writing an application to read the first line of a txt file and write to Excel.

The input line is like this, which has 94 characters in total, the last 8 can be blanks or 0's (the x's are actually blanks): 101x071000301x6759601771308202341F094101ACHxxxxxxxxxxxxxxxxxxxxFISxACHxMILWAUKEE‌​xxxxxxxx

When it prints, it correctly displays the x's as blank. Not sure about the last 8 blanks though.

The Console.WriteLine correctly outputs the string (which has blank spaces between characters), but when I try to extract the characters from the string I get this error:

'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index and length must refer to a location within 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?

Wiggler answered 6/9, 2013 at 23:36 Comment(3)
I'm aware Substrings start at zero. I carefully reviewed the index and length and they look OK to me. I also tried to change the index and length for the last field after your suggestion, but still get the same error...Wiggler
@Hing-LunMa: And if you do Console.WriteLine(input.Length), what is output? Also, do you know on which line that exception is thrown?Saury
@Jim good call. Printing the length leads me to look closer at the input file, and found out that they submitted the last 14 characters as empty instead of blanks. Thank you all for the help!Wiggler
L
10

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."

Therefore:

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

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

Law answered 6/9, 2013 at 23:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.