Creating Uri from base without trailing slash and relative parts

.net, uri

Solution

This is to be expected IMO. After all, consider the URI for "hello.jpg" relative to

 http://foo.com/site/index.html

It's

 http://foo.com/site/hello.jpg

right?

Now if you know that your user is entering a URI representing a directory, you can make sure that the string has a slash on the end. The problem comes if you don't know whether they're entering a directory name or not. Will just adding a slash if there isn't one already work for you?

string baseUri = new Uri(userUri + userUri.EndsWith("\\") ? "" : "\\");

That's assuming (based on your example) that they'll be using backslashes. Depending on your exact circumstance, you may need to handle forward slashes as well.

Problem

I am having a problem with Uri constructor. Results differ on whether base path ends with slash or not. ``` var baseWithSlash = new Uri("c:\\Temp\\"); var baseNoSlash = new Uri("c:\\Temp"); var relative = "MyApp"; var pathWithSlash = new Uri(baseWithSlash, relative); // file:///c:/Temp/MyApp var pathNoSlash = new Uri(baseNoSlash, relative); // file:///c:/MyApp ``` The first result is the one I expect even if there's no slash in base path. My main problem is that base path comes from user input. What's the best way to achieve correct result even if user specifies path without trailing slash?

Original source