The error message is pretty explicit:
index and count must refer to a location within the string
If you have a string with five characters in it then the index must be in the range 0 to 4, and the index plus the count must be less than 5. If either of those conditions fails, you will get an error because you are asking the system to process data outside the actual string data and it can't do that.
But we can't tell what is happening we have no idea what data you are feeding into that code, and that's going to be important to working out why you have a problem.
So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.
Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.
Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!