Path.Combine for URLs?

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

    Rules while combining URLs with a URI

    To avoid strange behaviour there's one rule to follow:

    • The path (directory) must end with '/'. If the path ends without '/', the last part is treated like a file-name, and it'll be concatenated when trying to combine with the next URL part.
    • There's one exception: the base URL address (without directory info) needs not to end with '/'
    • the path part must not start with '/'. If it start with '/', every existing relative information from URL is dropped...adding a string.Empty part path will remove the relative directory from the URL too!

    If you follow rules above, you can combine URLs with the code below. Depending on your situation, you can add multiple 'directory' parts to the URL...

            var pathParts = new string[] { destinationBaseUrl, destinationFolderUrl, fileName };
    
            var destination = pathParts.Aggregate((left, right) =>
            {
                if (string.IsNullOrWhiteSpace(right))
                    return left;
    
                return new Uri(new Uri(left), right).ToString();
            });
    

提交回复
热议问题