Path.Combine for URLs?

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

    I find the following useful and has the following features :

    • Throws on null or white space
    • Takes multiple params parameter for multiple Url segments
    • throws on null or empty

    Class

    public static class UrlPath
    {
       private static string InternalCombine(string source, string dest)
       {
          if (string.IsNullOrWhiteSpace(source))
             throw new ArgumentException("Cannot be null or white space", nameof(source));
    
          if (string.IsNullOrWhiteSpace(dest))
             throw new ArgumentException("Cannot be null or white space", nameof(dest));
    
          return $"{source.TrimEnd('/', '\\')}/{dest.TrimStart('/', '\\')}";
       }
    
       public static string Combine(string source, params string[] args) 
           => args.Aggregate(source, InternalCombine);
    }
    

    Tests

    UrlPath.Combine("test1", "test2");
    UrlPath.Combine("test1//", "test2");
    UrlPath.Combine("test1", "/test2");
    
    // Result = test1/test2
    
    UrlPath.Combine(@"test1\/\/\/", @"\/\/\\\\\//test2", @"\/\/\\\\\//test3\") ;
    
    // Result = test1/test2/test3
    
    UrlPath.Combine("/test1/", "/test2/", null);
    UrlPath.Combine("", "/test2/");
    UrlPath.Combine("/test1/", null);
    
    // Throws an ArgumentException
    

提交回复
热议问题