加入计划,网址,如果需要网址、计划

由网友(初如柠檬酸゛)分享简介:要由你可以做这样的字符串创建一个开放的:To create a Uri from a string you can do this:Uri u = new Uri("example.com");但问题是,如果该字符串(像上面的)不包含协议,你会得到一个异常:无效的URI:URI的格式无法确定为避免你应该确保该字符...

要由你可以做这样的字符串创建一个开放的:

To create a Uri from a string you can do this:

Uri u = new Uri("example.com");

但问题是,如果该字符串(像上面的)不包含协议,你会得到一个异常:无效的URI:URI的格式无法确定

为避免你应该确保该字符串的例外包括协议,象下面这样:

To avoid the exception you should secure the string includes a protocol, like below:

Uri u = new Uri("http://example.com");

但是,如果你把网址输入,你怎么能添加的协议,如果它丢失? 我的意思是除了一些的IndexOf /子字符串操作?

But if you take the url as input, how can you add the protocol if it's missing? I mean apart from some IndexOf/Substring manipulation?

东西典雅快?

推荐答案

您也可以使用UriBuilder:

You could also use UriBuilder:

public static Uri GetUri(this string s)
{
    return new UriBuilder(s).Uri;
}

从MSDN备注:

Remarks from MSDN:

该构造函数初始化的片段,主机,路径,端口,查询,计划和URI属性中设置的UriBuilder类的新实例作为URI中指定。

This constructor initializes a new instance of the UriBuilder class with the Fragment, Host, Path, Port, Query, Scheme, and Uri properties set as specified in uri.

如果URI不指定计划,该计划默认为HTTP:

阅读全文

相关推荐

最新文章