What is the safest way to get the last segment of a System.Uri
while excluding an optional end slash? For example, I have these URL:
http://example.com/test/12345
http://example.com/test/12345/
I wish to get just the "12345" from the final segment, however, calling Segments.Last()
will return different strings. In the first case I get "12345" but in the second case I get "12345/".
This is what I have, but doesn't seem very clean, and I'm worried I'm going to be violating the URI spec by not taking some weird edge cases into account:
public static string Test(Uri link)
{
return link.Segments.Last().Replace("/", "");
}
Edit: Absolutely ridiculous that this is being flagged for closing
You can simply use a TrimEnd()
:
public static string Test(Uri link)
{
return link.Segments.Last().TrimEnd('/');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With