Path.Combine for URLs?

前端 未结 30 2577
不思量自难忘°
不思量自难忘° 2020-11-22 14:28

Path.Combine is handy, but is there a similar function in the .NET framework for URLs?

I\'m looking for syntax like this:

Url.Combine(\"http://MyUrl.         


        
30条回答
  •  甜味超标
    2020-11-22 15:26

    Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.

    I first tried the new Uri(Uri baseUri, string relativeUri) approach, which failed for me because of URIs like http://www.mediawiki.org/wiki/Special:SpecialPages:

    new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")
    

    will result in Special:SpecialPages, because of the colon after Special that denotes a scheme.

    So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:

    public static string CombineUri(params string[] uriParts)
    {
        string uri = string.Empty;
        if (uriParts != null && uriParts.Length > 0)
        {
            char[] trims = new char[] { '\\', '/' };
            uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
            for (int i = 1; i < uriParts.Length; i++)
            {
                uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
            }
        }
        return uri;
    }
    

    Usage: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")

提交回复
热议问题