Jean Tehhe
Jean Tehhe

Reputation: 1357

Get the last path of URL

I'm using the following code which is working just fine for most of the services but some time in the URL last I got User;v=2;mp and I need to get just User,how should I handle it? I need some general solution since I guess in some other URL I can get different spacial charters

if the URL

https://ldmrrt.ct/odata/GBSRM/User;v=2;mp
string serviceName = _uri.Segments.LastOrDefault();

if the URL is https://ldmrrt.ct/odata/GBSRM/User its working fine...

Upvotes: 9

Views: 17625

Answers (2)

Kjartan
Kjartan

Reputation: 19151

Just replace:

string serviceName = _uri.Segments.LastOrDefault();

With:

string serviceName = _uri.Segments.LastOrDefault().Split(new[]{';'}).First();

If you need something more flexible, where you can specify what characters to include or skip, you could do something like this (slightly messy, you should probably extract parts of this as separate variables, etc):

// Note the _ and - characters in this example:
Uri _uri = new Uri("https://ldmrrt.ct/odata/GBSRM/User_ex1-ex2;v=2;mp");

// This will return a string: "User_ex1-ex2"
string serviceName =
        new string(_uri.Segments
                          .LastOrDefault()
                          .TakeWhile(c => Char.IsLetterOrDigit(c)
                                          || (new char[]{'_', '-'}).Contains(c))
                          .ToArray());

Update, in response to what I understand to be a question below :) :

You could just use a String.Replace() for that, or you could use filtering by doing something like this:

// Will return: "Userexex2v=2mp"
string serviceName = 
             new string(_uri.Segments
                            .LastOrDefault()       
                            .Where(c => 
                                    !Char.IsPunctuation(c) // Ignore punctuation
                                    // ..and ignore any "_" or "-":
                                    && !(new char[]{'_', '-'}).Contains(c)) 
                             .ToArray());

If you use this in production, mind you, be sure to clean it up a little, e.g. by splitting into several variables, and defining your char[]-array prior to usage.

Upvotes: 14

user4018366
user4018366

Reputation:

In your case you can try to split a "User;v=2;mp" string.

string [] split = words.Split(new Char [] { ';' });

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.

split.First();

or:

split[0];

Upvotes: 2

Related Questions