By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,639 Members | 2,276 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,639 IT Pros & Developers. It's quick & easy.

Substring Error

P: 22
Hey all,

This code:
Expand|Select|Wrap|Line Numbers
  1. AMessage = e.StackTrace.Substring(e.StackTrace.LastIndexOf("\\"), e.StackTrace.Length);
Produces this error:
Expand|Select|Wrap|Line Numbers
  1. Index and length must refer to a location within the string. Parameter name: length
I'm trying to retrieve the page name and line number of the given error (everything after the last slash in the StackTrace). I'm pretty sure my LastIndexOf and Length values are within range.

Any thoughts?
Dec 11 '08 #1
Share this Question
Share on Google+
4 Replies


nukefusion
Expert 100+
P: 221
Substring returns a part of a string starting from the index you specify for the length you specify. If the length you specify is longer than what is left of the string you'll get this error. As your starting from somewhere in the middle of the string you can't read e.StackTrace.Length chars from the rest of the string - there aren't that many. :)

You need to change your code to read:

Expand|Select|Wrap|Line Numbers
  1. int index = e.StackTrace.LastIndexOf("\\");
  2. AMessage = e.StackTrace.Substring(index, e.StackTrace.Length - index); 
  3.  
Dec 11 '08 #2

P: 22
Riiiight.... silly rabbit.. thx!
Dec 11 '08 #3

Plater
Expert 5K+
P: 7,872
Although the error sounds like you're trying to start from index -1, because that search string does not exist in the string.
Be sure to check to make sure index != -1
Dec 11 '08 #4

nukefusion
Expert 100+
P: 221
@Plater
Yes, that's a good suggestion. You may want to check that the index is valid before proceeding with the substring operation. In the above case the compiler has pointed out that the "length" parameter is the one at fault this time round, but you'd certainly want to employ Platers suggestion to make your code more robust.
Dec 11 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.