从基本建立开放的我们没有结尾的斜线及相关配件 [英] Creating Uri from base without trailing slash and relative parts

查看:186
本文介绍了从基本建立开放的我们没有结尾的斜线及相关配件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有URI构造一个问题。结果不同的基本路径是否与斜线结束与否。

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?

推荐答案

这是被国际海事组织的预期。毕竟,考虑到URI的hello.jpg相对于

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

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

这是

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

吧?

现在,如果你的知道的,你的用户正在进入一个URI重新presenting一个目录,你可以确保该字符串对最终斜线。问题来了,如果你不知道他们是否正在进入一个目录名或没有。会不会只是增加一个斜线,如果没有一个已经为你工作?

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.

这篇关于从基本建立开放的我们没有结尾的斜线及相关配件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆