Path.Combine for URLs?

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

    Here is my approach and I will use it for myself too:

    public static string UrlCombine(string part1, string part2)
    {
        string newPart1 = string.Empty;
        string newPart2 = string.Empty;
        string seperator = "/";
    
        // If either part1 or part 2 is empty,
        // we don't need to combine with seperator
        if (string.IsNullOrEmpty(part1) || string.IsNullOrEmpty(part2))
        {
            seperator = string.Empty;
        }
    
        // If part1 is not empty,
        // remove '/' at last
        if (!string.IsNullOrEmpty(part1))
        {
            newPart1 = part1.TrimEnd('/');
        }
    
        // If part2 is not empty,
        // remove '/' at first
        if (!string.IsNullOrEmpty(part2))
        {
            newPart2 = part2.TrimStart('/');
        }
    
        // Now finally combine
        return string.Format("{0}{1}{2}", newPart1, seperator, newPart2);
    }
    

提交回复
热议问题