C# .NET - Index and length must refer to a location within the string

Asked By chuck foss on 07-Jan-09 04:05 PM

Hi - when executing the following:

      tFileInputData =tFileInputDatab.Substring(2 - 1, Convert.ToInt32(StartUp.glbSetRecordSize)-1);

I receive this error:

Index and length must refer to a location within the string

My input data looks like this: BCQK07     00087920000120080801 00000164.33  00000000.00  00000164.33                                         

It is 132 bytes.

Can you tell me why I'm receiving the error and how I should correct the code?

Thank you very much.

Chuck Foss

                                         

re

Web Star replied to chuck foss on 07-Jan-09 11:09 PM

u should specify valid start index and length parameter value for substring method

here u give 2-1 is equal to 1 that valid but u should be check the value of Convert.ToInt32(StartUp.glbSetRecordSize)-1 and that should be less then the string length.

check second parameter to substring

Santhosh N replied to chuck foss on 07-Jan-09 11:47 PM

The error which you are getting is because the second string which you specified is larger than the the string which you are getting substring out of...

I suspect you specified the wrong parameters to the substring method

tFileInputData =tFileInputDatab.Substring(2 - 1, Convert.ToInt32(StartUp.glbSetRecordSize)-1);

I suppose this needs to be changed as this is giving a value which is either larger than the tFileInputDatab string or 0

read

C_A P replied to chuck foss on 08-Jan-09 04:23 AM
Are you trying to get a substring from a
string.

It looks like the you are getting out of range Error.
Lets say your string variable has 5 chars. Your string index range is from 0 to 4. If you try to get substring from index 1 to 5 you will get this error.
 
Try something like following..
strFirstName = strFirstName.Substring(1,lenFirstName -1); //-1 is important
try this link
C_A P replied to chuck foss on 08-Jan-09 04:26 AM

http://www.aspose.com/community/forums/thread/15035/error-index-and-length-must-refer-to-a-location-within-the-string.parameter-name-length.aspx

http://bytes.com/groups/net-c/514628-problem-substing-index-length-must-refer-location