Substring Error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mugs321
    New Member
    • Sep 2006
    • 22

    Substring Error

    Hey all,

    This code:
    Code:
    AMessage = e.StackTrace.Substring(e.StackTrace.LastIndexOf("\\"), e.StackTrace.Length);
    Produces this error:
    Code:
    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?
  • nukefusion
    Recognized Expert New Member
    • Mar 2008
    • 221

    #2
    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.Le ngth chars from the rest of the string - there aren't that many. :)

    You need to change your code to read:

    Code:
    int index = e.StackTrace.LastIndexOf("\\");
    AMessage = e.StackTrace.Substring(index, e.StackTrace.Length - index);

    Comment

    • Mugs321
      New Member
      • Sep 2006
      • 22

      #3
      Riiiight.... silly rabbit.. thx!

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        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

        Comment

        • nukefusion
          Recognized Expert New Member
          • Mar 2008
          • 221

          #5
          Originally posted by Plater
          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
          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.

          Comment

          Working...