Path.Combine for URLs?

2019-01-01 04:22发布

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.com/", "/Images/Image.jpg")

which would return:

"http://MyUrl.com/Images/Image.jpg"

30条回答
裙下三千臣
2楼-- · 2019-01-01 04:54

Why not just use the following.

System.IO.Path.Combine(rootUrl, subPath).Replace(@"\", "/")
查看更多
浮光初槿花落
3楼-- · 2019-01-01 04:54

We use the following simple helper method to join an arbitrary number of URL parts together:

public static string JoinUrlParts(params string[] urlParts)
{
    return string.Join("/", urlParts.Where(up => !string.IsNullOrEmpty(up)).ToList().Select(up => up.Trim('/')).ToArray());
}

Note, that it doesn't support '../../something/page.htm'-style relative URLs!

查看更多
何处买醉
4楼-- · 2019-01-01 04:55

I found that the Uri constructor flips '\' into '/'. So you can also use Path.Combine, with the Uri constructor.

 Uri baseUri = new Uri("http://MyUrl.com");
 string path = Path.Combine("Images", "Image.jpg");
 Uri myUri = new Uri(baseUri, path);
查看更多
何处买醉
5楼-- · 2019-01-01 04:56

I just put together a small extension method:

public static string UriCombine (this string val, string append)
        {
            if (String.IsNullOrEmpty(val)) return append;
            if (String.IsNullOrEmpty(append)) return val;
            return val.TrimEnd('/') + "/" + append.TrimStart('/');
        }

It can be used like this:

"www.example.com/".UriCombine("/images").UriCombine("first.jpeg");
查看更多
孤独寂梦人
6楼-- · 2019-01-01 04:57

This may be a suitably simple solution:

public static string Combine(string uri1, string uri2)
{
    uri1 = uri1.TrimEnd('/');
    uri2 = uri2.TrimStart('/');
    return string.Format("{0}/{1}", uri1, uri2);
}
查看更多
像晚风撩人
7楼-- · 2019-01-01 04:57

Based on the sample URL you provided, I'm going to assume you want to combine URLs that are relative to your site.

Based on this assumption I'll propose this solution as the most appropriate response to your question which was: "Path.Combine is handy, is there a similar function in the framework for URLs?"

Since there the is a similar function in the framework for URLs I propose the correct is: "VirtualPathUtility.Combine" method. Here's the MSDN reference link: VirtualPathUtility.Combine Method

There is one caveat: I believe this only works for URLs relative to your site (that is, you cannot use it to generate links to another web site. For example, var url = VirtualPathUtility.Combine("www.google.com", "accounts/widgets");).

查看更多
登录 后发表回答