Path.Combine for URLs?

前端 未结 30 2604
不思量自难忘°
不思量自难忘° 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:11

    Witty example, Ryan, to end with a link to the function. Well done.

    One recommendation Brian: if you wrap this code in a function, you may want to use a UriBuilder to wrap the base URL prior to the TryCreate call.

    Otherwise, the base URL MUST include the scheme (where the UriBuilder will assume http://). Just a thought:

    public string CombineUrl(string baseUrl, string relativeUrl) {
        UriBuilder baseUri = new UriBuilder(baseUrl);
        Uri newUri;
    
        if (Uri.TryCreate(baseUri.Uri, relativeUrl, out newUri))
            return newUri.ToString();
        else
            throw new ArgumentException("Unable to combine specified url values");
    }
    

提交回复
热议问题