public static string MakeValidUri(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(nameof(path));
}
Uri uri;
string validUri;
if (Uri.TryCreate(path, UriKind.Absolute, out uri))
{
validUri = uri.AbsoluteUri;
}
else if (Uri.TryCreate(path, UriKind.Relative, out uri))
{
UriBuilder builder = new UriBuilder("http", "www.example.com", 80, path);
validUri = builder.Uri.AbsolutePath;
// Since what we actually want is a relative path, strip the leading "/"
// from the AbsolutePath -- unless the input string started with "/".
if (!path.StartsWith("/", StringComparison.Ordinal) &&
!path.StartsWith(@"\", StringComparison.Ordinal))
{
validUri = validUri.Substring(1);
// When the UriBuilder constructs an absolute URI, it strips any
// leading "." and ".." segments ("dot-segments", as RFC 3986 calls
// them). Glue them back on so we don't lose the relative path
// information.
string leadingDotSegments = GetLeadingDotSegments(path);
if (!string.IsNullOrEmpty(leadingDotSegments))
{
validUri = leadingDotSegments + validUri;
}
}
}
else
{
validUri = System.Net.WebUtility.UrlEncode(path);
}
return validUri;
}