user496949
user496949

Reputation: 86185

Relative path using Uri

Uri test = new Uri(new Uri("http://www.google.com/test"), "foo");

returns http://www.google.com/foo

but Uri test = new Uri(new Uri("http://www.google.com/test/"), "foo");

returns http://www.google.com/foo/test

It seems the last slash is very important, is there a unified way to return http://www.google.com/foo/test in all cases

Upvotes: 5

Views: 1100

Answers (3)

Ramesh
Ramesh

Reputation: 13266

Uri test = new Uri(new Uri(GetSafeURIString("http://www.google.com/test")), "foo");



private static string GetSafeURIString(uri)
{
   if(uri == null)
       return uri;
   else
       return uri.EndsWith("/") ? uri : uri + "/";
}

Upvotes: 0

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263147

Well, you need to ensure that your base URI ends with a / character:

public Uri CombineUris(string baseUri, string relativeUri)
{
    if (!baseUri.EndsWith("/")) {
        baseUri += "/";
    }
    return new Uri(new Uri(baseUri), relativeUri);
}

Upvotes: 2

khachik
khachik

Reputation: 28703

Make sure to pass the root URI with the trailing /. Last slash is very important. Consider http://www.example.com/foo/bar.html, bar2.html. It should be resolved to http://www.example.com/foo/bar2.html.

Upvotes: 1

Related Questions