tags:

views:

165

answers:

2

Hi!

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\"); \\ "StackOverflow colorer workaround :)
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?

A: 

Make sure the first part has a trailing slash (i.e: check for it).

Noon Silk
+1  A: 

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.

Jon Skeet
Appending slash if there isn't already one is fine by me. User may be using back and forward slashes - I just didn't want to write kind of code you wrote but seems like it's inevitable. Thanks!
Konstantin Spirin
Btw, interesting note about hello.jpg relative to index.html. I have never looked at this angle.
Konstantin Spirin