URL的Path.Combine嗎?

Path.Combine很方便,可是.NET框架中是否有用於URL的相似功能? api

我正在尋找這樣的語法: 框架

Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")

這將返回: 函數

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


#1樓

機智的例子Ryan以指向該函數的連接結尾。 作得好。 url

一條建議Brian:若是將此代碼包裝在一個函數中,則可能須要使用UriBuilder在TryCreate調用以前包裝基本URL。 spa

不然,基本URL必須包含方案(UriBuilder將採用http://)。 只是一個想法: code

public string CombineUrl(string baseUrl, string relativeUrl) {
    UriBuilder baseUri = new UriBuilder(baseUrl);
    Uri newUri;

    if (Uri.TryCreate(baseUri.Uri, relativeUrl, out newUri))
        return newUri.ToString();
    else
        throw new ArgumentException("Unable to combine specified url values");
}

#2樓

用這個: orm

public static class WebPath
{
    public static string Combine(params string[] args)
    {
        var prefixAdjusted = args.Select(x => x.StartsWith("/") && !x.StartsWith("http") ? x.Substring(1) : x);
        return string.Join("/", prefixAdjusted);
    }
}

#3樓

這多是一個適當的簡單解決方案: htm

public static string Combine(string uri1, string uri2)
{
    uri1 = uri1.TrimEnd('/');
    uri2 = uri2.TrimStart('/');
    return string.Format("{0}/{1}", uri1, uri2);
}

#4樓

Uri具備應爲您執行此操做的構造函數: new Uri(Uri baseUri, string relativeUri) ip

這是一個例子:

Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");

編輯注意:請注意,此方法沒法按預期工做。 在某些狀況下,它能夠削減baseUri的一部分。 查看評論和其餘答案。


#5樓

我結合了之前的全部答案:

public static string UrlPathCombine(string path1, string path2)
    {
        path1 = path1.TrimEnd('/') + "/";
        path2 = path2.TrimStart('/');

        return Path.Combine(path1, path2)
            .Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
    }

    [TestMethod]
    public void TestUrl()
    {
        const string P1 = "http://msdn.microsoft.com/slash/library//";
        Assert.AreEqual("http://msdn.microsoft.com/slash/library/site.aspx", UrlPathCombine(P1, "//site.aspx"));

        var path = UrlPathCombine("Http://MyUrl.com/", "Images/Image.jpg");

        Assert.AreEqual(
            "Http://MyUrl.com/Images/Image.jpg",
            path);
    }
相關文章
相關標籤/搜索