HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Path.Combine for URLs?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
pathcombineurlsfor

Problem

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"

Solution

There is a Todd Menier's comment above that Flurl includes a Url.Combine.

More details:

Url.Combine is basically a Path.Combine for URLs, ensuring one
and only one separator character between parts:

var url = Url.Combine(
    "http://MyUrl.com/",
    "/too/", "/many/", "/slashes/",
    "too", "few?",
    "x=1", "y=2"
// result: "http://www.MyUrl.com/too/many/slashes/too/few?x=1&y=2"


Get Flurl.Http on NuGet:

PM> Install-Package Flurl.Http

Or get the stand-alone URL builder without the HTTP features:

PM> Install-Package Flurl

Code Snippets

var url = Url.Combine(
    "http://MyUrl.com/",
    "/too/", "/many/", "/slashes/",
    "too", "few?",
    "x=1", "y=2"
// result: "http://www.MyUrl.com/too/many/slashes/too/few?x=1&y=2"

Context

Stack Overflow Q#372865, score: 146

Revisions (0)

No revisions yet.