Path.Combine for URLs?

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

    There's already some great answers here. Based on mdsharpe suggestion, here's an extension method that can easily be used when you want to deal with Uri instances:

    using System;
    using System.Linq;
    
    public static class UriExtensions
    {
        public static Uri Append(this Uri uri, params string[] paths)
        {
            return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
        }
    }
    

    And usage example:

    var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;
    

    This will produce http://example.com/subpath/part1/part2

提交回复
热议问题