c# - 如果需要,将方案添加到 URL

标签 c# .net uri

要从字符串创建 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/

相关文章:

c# - .NET 垃圾收集器之谜

android - 在 ImageView 中显示存储在内部存储器中的图像?我究竟做错了什么?

c# - 如果将字符串引用设置为引号中的字符串,编译器是否会创建额外的字符串?

c# - 如何减少多个嵌套的 foreach block

c# - 如何检查一个字符串是否匹配多个字符串并根据匹配返回值

c# - 未找到 System.Net.SecurityProtocolType.Tls12 定义

c# - 以编程方式在 MS Word 中打开 xml 文件

android - UriMatcher 不匹配模式

c# - 如何在 Selenium 3.1.0 中设置 ImplicitWait

C# 解析对象的 JSON 数组