Add scheme to URL if needed

Interestingly, although Uri and UriBuilder completely mangle any url without a scheme, WebProxy does it right.

So just call:

new WebProxy(proxy.ProxyServer).Address

You could also use UriBuilder:

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

Remarks from 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:".


If you just want to add the scheme, without validating the URL, the fastest/easiest way is to use string lookups, eg:

string url = "mydomain.com";
if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) url = "http://" + url;

A better approach would be to use Uri to also validate the URL using the TryCreate method:

string url = "mydomain.com";
Uri uri;
if ((Uri.TryCreate(url, UriKind.Absolute, out uri) || Uri.TryCreate("http://" + url, UriKind.Absolute, out uri)) &&
    (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
{
    // Use validated URI here
}

As @JanDavidNarkiewicz pointed out in the comments, validating the Scheme is necessary to guard against invalid schemes when a port is specified without scheme, e.g. mydomain.com:80.


My solution was for protocall-less urls to make sure they have protocal was regex :

Regex.Replace(s, @"^\/\/", "http://");

Tags:

C#

.Net

Uri