 <p>The second parameter in <a href="https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx" rel="nofollow"><code>Substring</code></a> is the length of the substring, not the end index.</p> <p>You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.</p> <p>Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:</p> <pre><code>var prefix = "www.example.com/"; var suffix = ".jpg"; string url = "www.example.com/aaa/bbb.jpg"; if (url.StartsWith(prefix) &amp;&amp; url.EndsWith(suffix) &amp;&amp; url.Length &gt;= (prefix.Length + suffix.Length)) { string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length); Console.WriteLine(newString); } else //handle invalid state </code></pre>