1

I was recently looking at this SO thread: Path.Combine for URLs? and thought that maybe I could create something like Path.Combine. So I wrote:

    private string combineUrlParts(params string[] urlParts)
    {
        var myUrl = new Uri(urlParts[0]);
        for (int x = 1; x < urlParts.Length; x++)
        {
          if (!Uri.TryCreate(myUrl, urlParts[x], out myUrl))
          {
              // Log failure
          }
        }
        return myUrl.ToString();
    }

The idea being to list a baseUrl ("http://someurl.com/"), a path ("/company/5/"), and another part ("/Financials/index.aspx") and have it all magically combined.

This method almost works. The first time thru the loop, it combines the base Url and the first path just fine. But the 2nd time thru the loop, Uri.TryCreate just overwrites the Path with the second part yielding:

http://someurl.com/Financials/index.aspx

instead of what I was expecting:

http://someurl.com/company/5/Financials/index.aspx

Any ideas what's going on here?

Community
  • 1
  • 1
Pretzel
  • 8,141
  • 16
  • 59
  • 84

1 Answers1

1

I think passing the same uri to TryCreate is causing a problem. Try this:

Uri t;
if (!Uri.TryCreate(myUrl, urlParts[x], out t))
{
          // Log failure
}
myUrl = t;
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73