要从字符串创建 Uri,您可以这样做:
Uri u = new Uri("example.com");
但问题是如果字符串(如上面的字符串)不包含协议(protocol),您将得到一个异常:“Invalid URI: The format of the URI could not be determined.
”
为避免异常,您应该确保字符串包含一个协议(protocol),如下所示:
Uri u = new Uri("http://example.com");
但是如果把url作为输入,协议(protocol)少了怎么添加呢?
我的意思是除了一些 IndexOf/Substring 操作之外?
优雅快速的东西?
最佳答案
你也可以使用 UriBuilder
:
public static Uri GetUri(this string s)
{
return new UriBuilder(s).Uri;
}
来自 MSDN 的注释:
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.
If uri does not specify a scheme, the scheme defaults to "http:".
关于c# - 如果需要,将方案添加到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5289739/