开发者

Creating Uri from base without trailing slash and relative parts

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:/T开发者_C百科emp/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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜