Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm getting this error index was out of range. must be nonnegative and less than the size of the collection in c#
parameter: index

Can anyone help me with this?

C#
private static string GetTxtBtwn(string input, string start, string end, int startIndex, bool UseLastIndexOf)
        {
            int index1 = UseLastIndexOf ? input.LastIndexOf(start, startIndex) :
                                          input.IndexOf(start, startIndex);
            if (index1 == -1) return "";
            index1 += start.Length;
            int index2 = input.IndexOf(end, index1);
            if (index2 == -1) return input.Substring(index1);
            return input.Substring(index1, index2 - index1);

            
        }
Posted

Exactly why is up to your data, but the mechanics of getting the problem are simple:
What happens if the end is found before the start, or as part of the start string?
I.e. if input is "1234567890" and start is "345678" and end is "23", then
index1 == 8
index2 == 1
So your length will be negative. That won't cause the exact error you are getting this time, but it's an example of a "route to failure" which depends on your data to work out exactly what the problem is.

If you get a problem like this, use the debugger, and look at your data. Step through line by line and try to spot what values are what.
 
Share this answer
 
Allthough I do not agree with the analysis of OriginalGriff, you are starting your search for the second substring after the end of the first string so his assertion should not happen, i do agree with his statement: depends on your data so use the debugger.

Are you sure the parameter startindex you are providing to the method is not past the end of the string? That would throw this error at the line looking for your index1.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900