Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing end slash from Uri.Segment.Last()?

Tags:

c#

.net

uri

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

like image 891
user9993 Avatar asked Dec 04 '22 20:12

user9993


1 Answers

You can simply use a TrimEnd():

public static string Test(Uri link)
{
    return link.Segments.Last().TrimEnd('/');
}
like image 114
René Vogt Avatar answered Dec 24 '22 15:12

René Vogt