Path.Combine for URLs?












1111















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"










share|improve this question




















  • 12





    Flurl includes a Url.Combine method that does just that.

    – Todd Menier
    Feb 21 '14 at 6:18






  • 1





    Actually, the // is handled by the routing of the website or server and not by the browser. It will send what you put into the address bar. That's why we get problems when we type htp:// instead of http:// So the // can cause major problems on some sites. I am writing a .dll for a crawler which handles a particular website which throws a 404 if you have // in the url.

    – Dave Gordon
    Jul 7 '14 at 8:11
















1111















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"










share|improve this question




















  • 12





    Flurl includes a Url.Combine method that does just that.

    – Todd Menier
    Feb 21 '14 at 6:18






  • 1





    Actually, the // is handled by the routing of the website or server and not by the browser. It will send what you put into the address bar. That's why we get problems when we type htp:// instead of http:// So the // can cause major problems on some sites. I am writing a .dll for a crawler which handles a particular website which throws a 404 if you have // in the url.

    – Dave Gordon
    Jul 7 '14 at 8:11














1111












1111








1111


128






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"










share|improve this question
















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"







c# .net asp.net url path






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 3 '15 at 15:01









Peter Mortensen

13.8k1987113




13.8k1987113










asked Dec 16 '08 at 21:42









Brian MacKayBrian MacKay

17.2k1370109




17.2k1370109








  • 12





    Flurl includes a Url.Combine method that does just that.

    – Todd Menier
    Feb 21 '14 at 6:18






  • 1





    Actually, the // is handled by the routing of the website or server and not by the browser. It will send what you put into the address bar. That's why we get problems when we type htp:// instead of http:// So the // can cause major problems on some sites. I am writing a .dll for a crawler which handles a particular website which throws a 404 if you have // in the url.

    – Dave Gordon
    Jul 7 '14 at 8:11














  • 12





    Flurl includes a Url.Combine method that does just that.

    – Todd Menier
    Feb 21 '14 at 6:18






  • 1





    Actually, the // is handled by the routing of the website or server and not by the browser. It will send what you put into the address bar. That's why we get problems when we type htp:// instead of http:// So the // can cause major problems on some sites. I am writing a .dll for a crawler which handles a particular website which throws a 404 if you have // in the url.

    – Dave Gordon
    Jul 7 '14 at 8:11








12




12





Flurl includes a Url.Combine method that does just that.

– Todd Menier
Feb 21 '14 at 6:18





Flurl includes a Url.Combine method that does just that.

– Todd Menier
Feb 21 '14 at 6:18




1




1





Actually, the // is handled by the routing of the website or server and not by the browser. It will send what you put into the address bar. That's why we get problems when we type htp:// instead of http:// So the // can cause major problems on some sites. I am writing a .dll for a crawler which handles a particular website which throws a 404 if you have // in the url.

– Dave Gordon
Jul 7 '14 at 8:11





Actually, the // is handled by the routing of the website or server and not by the browser. It will send what you put into the address bar. That's why we get problems when we type htp:// instead of http:// So the // can cause major problems on some sites. I am writing a .dll for a crawler which handles a particular website which throws a 404 if you have // in the url.

– Dave Gordon
Jul 7 '14 at 8:11












32 Answers
32






active

oldest

votes













1 2
next












15














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://foo.com/",
"/too/", "/many/", "/slashes/",
"too", "few?",
"x=1", "y=2"
// result: "http://www.foo.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






share|improve this answer





















  • 3





    Well, this question gets a lot of traffic, and the answer with 1000+ upvotes does not actually work in all cases. Years later, I actually use Flurl for this, so I am accepting this one. It seems to work in all cases I have encountered. If people don't want to take a dependency, I posted an answer that also works fine.

    – Brian MacKay
    Nov 28 '18 at 15:33













  • and if you dont use Flurl and would perfer a lightweight version, github.com/jean-lourenco/UrlCombine

    – lizzy91
    Feb 1 at 19:59



















1068














Uri has a constructor that should do this for you: new Uri(Uri baseUri, string relativeUri)



Here's an example:



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


Note from editor: Beware, this method does not work as expected. It can cut part of baseUri in some cases. See comments and other answers.






share|improve this answer





















  • 332





    I like the use of the Uri class, unfortunately it will not behave like Path.Combine as the OP asked. For example new Uri(new Uri("test.com/mydirectory/"), "/helloworld.aspx").ToString() gives you "test.com/helloworld.aspx"; which would be incorrect if we wanted a Path.Combine style result.

    – Doctor Jones
    Oct 28 '10 at 15:20






  • 169





    It's all in the slashes. If the relative path part starts with a slash, then it behaves as you described. But, if you leave the slash out, then it works the way you'd expect (note the missing slash on the second parameter): new Uri(new Uri("test.com/mydirectory/"), "helloworld.aspx").ToString() results in "test.com/mydirectory/helloworld.aspx". Path.Combine behaves similarly. If the relative path parameter starts with a slash, it only returns the relative path and doesn't combine them.

    – Joel Beckham
    Oct 28 '10 at 22:11








  • 61





    If your baseUri happened to be "test.com/mydirectory/mysubdirectory" then the result would be "test.com/mydirectory/helloworld.aspx" instead of "test.com/mydirectory/mysubdirectory/helloworld.aspx". The subtle difference is the lack of trailing slash on the first parameter. I'm all for using existing framework methods, if I have to have the trailing slash there already then I think that doing partUrl1 + partUrl2 smells a lot less - I could've potentially been chasing that trailing slash round for quite a while all for the sake of not doing string concat.

    – Carl
    Jan 12 '11 at 16:10






  • 58





    The only reason I want a URI combine method is so that I don't have to check for the trailing slash. Request.ApplicationPath is '/' if your application is at the root, but '/foo' if it's not.

    – nickd
    Mar 25 '11 at 16:44






  • 19





    I -1 this answer because this doesn't answer the problem. When you want to combine url, like when you want to use Path.Combine, you don't want to care about the trailing /. and with this, you have to care. I prefer solution of Brian MacKay or mdsharpe above

    – Baptiste Pernet
    Apr 21 '11 at 15:56



















137














You use Uri.TryCreate( ... ) :



Uri result = null;

if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
{
Console.WriteLine(result);
}


Will return:




http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx







share|improve this answer



















  • 47





    +1: This is good, although I have an irrational problem with the output parameter. ;)

    – Brian MacKay
    Oct 29 '09 at 14:24






  • 10





    @Brian: if it helps, all TryXXX methods (int.TryParse, DateTime.TryParseExact) have this output param to make it easier to use them in an if-statement. Btw, you don't have to initialize the variable as Ryan did in this example.

    – Abel
    Aug 26 '10 at 22:11






  • 31





    This answer suffers the same problem as Joel's: joining test.com/mydirectory/ and /helloworld.aspx will result in test.com/helloworld.aspx which is seemingly not what you want.

    – Matt Kocaj
    Aug 27 '13 at 2:05






  • 2





    Hi, this failed for following : if (Uri.TryCreate(new Uri("localhost/MyService/"), "/Event/SomeMethod?abc=123", out result)) { Console.WriteLine(result); } It is showing me result as : localhost/Event/SomeMethod?abc=123 Note: "http://" is replaced from base Uri here by stackoverflow

    – Faisal Mq
    Nov 28 '13 at 8:45








  • 3





    @FaisalMq This is the correct behavior, since you passed a root-relative second parameter. If you had left out the leading / on the second parameter, you'd have gotten the result you expected.

    – Tom Lint
    Jan 24 '14 at 9:17



















131














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);
}





share|improve this answer



















  • 7





    +1: Although this doesn't handle relative-style paths (../../whatever.html), I like this one for its simplicity. I would also add trims for the '' character.

    – Brian MacKay
    May 8 '10 at 15:55






  • 3





    See my answer for a more fully fleshed out version of this.

    – Brian MacKay
    May 12 '10 at 13:46



















116














There's already some great answers here. Based on mdsharpe suggestion, here's an extension method that can easily be used when you want to deal with Uri instances:



using System;
using System.Linq;

public static class UriExtensions
{
public static Uri Append(this Uri uri, params string paths)
{
return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
}
}


And usage example:



var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;


This will produce http://example.com/subpath/part1/part2






share|improve this answer





















  • 2





    This solution makes it trivial to write a UriUtils.Combine("base url", "part1", "part2", ...) static method that is very similar to Path.Combine(). Nice!

    – angularsen
    Nov 19 '11 at 15:23











  • To support relative URIs I had to use ToString() instead of AbsoluteUri and UriKind.AbsoluteOrRelative in the Uri constructor.

    – angularsen
    Nov 20 '11 at 19:34













  • Thanks for the tip about relative Uris. Unfortunately Uri doesn't make it easy to deal with relative paths as there is always some mucking about with Request.ApplicationPath involved. Perhaps you could also try using new Uri(HttpContext.Current.Request.ApplicationPath) as a base and just call Append on it? This will give you absolute paths but should work anywhere within site structure.

    – Ales Potocnik Hahonina
    Nov 21 '11 at 12:03











  • Great. Glad it helped someone else. Been using this for some time now and haven't had any issues.

    – Ales Potocnik Hahonina
    Jul 8 '13 at 8:58











  • I also added check if any of paths to append are not null nor empty string.

    – n.podbielski
    Jan 15 '16 at 10:13



















82














Ryan Cook's answer is close to what I'm after and may be more appropriate for other developers. However, it adds http:// to the beginning of the string and in general it does a bit more formatting than I'm after.



Also, for my use cases, resolving relative paths is not important.



mdsharp's answer also contains the seed of a good idea, although that actual implementation needed a few more details to be complete. This is an attempt to flesh it out (and I'm using this in production):



C#



public string UrlCombine(string url1, string url2)
{
if (url1.Length == 0) {
return url2;
}

if (url2.Length == 0) {
return url1;
}

url1 = url1.TrimEnd('/', '\');
url2 = url2.TrimStart('/', '\');

return string.Format("{0}/{1}", url1, url2);
}


VB.NET



Public Function UrlCombine(ByVal url1 As String, ByVal url2 As String) As String
If url1.Length = 0 Then
Return url2
End If

If url2.Length = 0 Then
Return url1
End If

url1 = url1.TrimEnd("/"c, ""c)
url2 = url2.TrimStart("/"c, ""c)

Return String.Format("{0}/{1}", url1, url2)
End Function


This code passes the following test, which happens to be in VB:



<TestMethod()> Public Sub UrlCombineTest()
Dim target As StringHelpers = New StringHelpers()

Assert.IsTrue(target.UrlCombine("test1", "test2") = "test1/test2")
Assert.IsTrue(target.UrlCombine("test1/", "test2") = "test1/test2")
Assert.IsTrue(target.UrlCombine("test1", "/test2") = "test1/test2")
Assert.IsTrue(target.UrlCombine("test1/", "/test2") = "test1/test2")
Assert.IsTrue(target.UrlCombine("/test1/", "/test2/") = "/test1/test2/")
Assert.IsTrue(target.UrlCombine("", "/test2/") = "/test2/")
Assert.IsTrue(target.UrlCombine("/test1/", "") = "/test1/")
End Sub





share|improve this answer





















  • 4





    Talking of details: what about the mandatory ArgumentNullException("url1") if the argument is Nothing? Sorry, just being picky ;-). Note that a backslash has nothing to do in a URI (and if it is there, it should not be trimmed), so you can remove that from your TrimXXX.

    – Abel
    Aug 26 '10 at 22:21






  • 4





    you can use params string and recursively join them to allow more than 2 combinations

    – Jaider
    Jun 12 '12 at 22:47






  • 4





    I sure wish this was in the Base Class Library like Path.Combine.

    – Uriah Blatherwick
    Aug 18 '14 at 18:30






  • 1





    @MarkHurd I edited the code again, so that it's behaviorally the same as the C#, and syntactically equivalent as well.

    – JJS
    Jul 7 '16 at 19:23






  • 1





    @BrianMacKay i broke it, markhurd pointed out my mistake and rolled back, i updated again... cheers

    – JJS
    Jul 11 '16 at 13:28



















32














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");).






share|improve this answer


























  • +1 because it's close to what I'm looking for, although it would be ideal if it would work for any old url. I double it will get much more elegant than what mdsharpe proposed.

    – Brian MacKay
    Mar 29 '10 at 21:28






  • 2





    The caveat is correct, it cannot work with absolute uris and the result is always relative from the root. But it has an added benefit, it processes the tilde, as with "~/". This makes it a shortcut for Server.MapPath and combining.

    – Abel
    Aug 26 '10 at 22:18





















29














Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.



I first tried the new Uri(Uri baseUri, string relativeUri) approach, which failed for me because of URIs like http://www.mediawiki.org/wiki/Special:SpecialPages:



new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")


will result in Special:SpecialPages, because of the colon after Special that denotes a scheme.



So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:



public static string CombineUri(params string uriParts)
{
string uri = string.Empty;
if (uriParts != null && uriParts.Count() > 0)
{
char trims = new char { '\', '/' };
uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
for (int i = 1; i < uriParts.Count(); i++)
{
uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
}
}
return uri;
}


Usage: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")






share|improve this answer





















  • 1





    +1: Now we're talking... I'm going to try this out. This might even end up being the new accepted answer. After trying to new Uri() method I really don't like it. Too finnicky.

    – Brian MacKay
    Jul 18 '11 at 14:23











  • This is exactly what I needed! Was not a fan of having to care where I put trailing slashes, etc...

    – Gromer
    Aug 6 '12 at 21:52











  • +1 for rolling in the null checking so it won't blow up.

    – NightOwl888
    Mar 6 '14 at 13:34



















22














Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\", "/")





share|improve this answer



















  • 7





    path.Replace(Path.DirectorySeparatorChar, '/');

    – Jaider
    Jun 12 '12 at 22:51






  • 4





    path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)

    – SliverNinja - MSFT
    Aug 16 '12 at 14:31








  • 1





    To get it to wrk u must remove first / in second arg ie "/Images" - / Path.Combine("Http://MyUrl.com", "Images/Image.jpg")

    – Per G
    Apr 25 '13 at 10:43








  • 7





    @SliverNinja That's not correct The value of this field is a backslash ('') on UNIX, and a slash ('/') on Windows and Macintosh operating systems. When using Mono on a Linux system, you'd get the wrong separator.

    – Stijn
    Mar 13 '14 at 10:01






  • 3





    All yall that are geeking out on the Directory Separator are forgetting that the strings could have come from a different OS than you are on now. Just replace backslash with forward slash and you're covered.

    – JeremyWeir
    Jul 26 '16 at 22:43



















16














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");





share|improve this answer

































    11














    Witty example, Ryan, to end with a link to the function. Well done.



    One recommendation Brian: if you wrap this code in a function, you may want to use a UriBuilder to wrap the base URL prior to the TryCreate call.



    Otherwise, the base URL MUST include the scheme (where the UriBuilder will assume http://). Just a thought:



    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");
    }





    share|improve this answer

































      8














      Combining multiple parts of a URL could be a little bit tricky. You can use the two-parameter constructor Uri(baseUri, relativeUri), or you can use the Uri.TryCreate() utility function.



      In either case, you might end up returning an incorrect result because these methods keep on truncating the relative parts off of the first parameter baseUri, i.e. from something like http://google.com/some/thing to http://google.com.



      To be able to combine multiple parts into a final URL, you can copy the two functions below:



          public static string Combine(params string parts)
      {
      if (parts == null || parts.Length == 0) return string.Empty;

      var urlBuilder = new StringBuilder();
      foreach (var part in parts)
      {
      var tempUrl = tryCreateRelativeOrAbsolute(part);
      urlBuilder.Append(tempUrl);
      }
      return VirtualPathUtility.RemoveTrailingSlash(urlBuilder.ToString());
      }

      private static string tryCreateRelativeOrAbsolute(string s)
      {
      System.Uri uri;
      System.Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri);
      string tempUrl = VirtualPathUtility.AppendTrailingSlash(uri.ToString());
      return tempUrl;
      }


      Full code with unit tests to demonstrate usage can be found at https://uricombine.codeplex.com/SourceControl/latest#UriCombine/Uri.cs



      I have unit tests to cover the three most common cases:



      Enter image description here






      share|improve this answer





















      • 1





        Looks pretty good to me. Although you could replace the I loop with a foreach loop for better clarity.

        – Chris Marisic
        May 1 '14 at 18:55











      • Thanks Chris. I have just changed my code to use Foreach.

        – Believe2014
        May 2 '14 at 4:03






      • 1





        +1 for all the extra effort. I need to maintain this question a bit for some of the higher voted answers, you have thrown down the gauntlet. ;)

        – Brian MacKay
        May 4 '14 at 11:42













      • Sorry, but not enough. Works in the few cases you show but far from being usable in al combinations. For instance, colons in the path will cause harm.

        – Gábor
        May 13 '18 at 20:43











      • Can you please give an example of what you mean? I will be happy to fix the issue and help the next users.

        – Believe2014
        May 14 '18 at 21:23



















      7














      I found UriBuilder worked really well for this sort of thing:



      UriBuilder urlb = new UriBuilder("http", _serverAddress, _webPort, _filePath);
      Uri url = urlb.Uri;
      return url.AbsoluteUri;


      See UriBuilder Class - MSDN for more constructors and documentation.






      share|improve this answer

































        7














        An easy way to combine them and ensure it's always correct is:



        string.Format("{0}/{1}", Url1.Trim('/'), Url2);





        share|improve this answer


























        • +1, although this is very similiar to mdsharpe's answer, which I improved upon in my answer. This version works great unless Url2 starts with / or , or Url1 accidentally ends in , or either one is empty! :)

          – Brian MacKay
          May 12 '10 at 23:57



















        4














        Here's Microsoft's (OfficeDev PnP) method UrlUtility.Combine:



            const char PATH_DELIMITER = '/';

        /// <summary>
        /// Combines a path and a relative path.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="relative"></param>
        /// <returns></returns>
        public static string Combine(string path, string relative)
        {
        if(relative == null)
        relative = String.Empty;

        if(path == null)
        path = String.Empty;

        if(relative.Length == 0 && path.Length == 0)
        return String.Empty;

        if(relative.Length == 0)
        return path;

        if(path.Length == 0)
        return relative;

        path = path.Replace('\', PATH_DELIMITER);
        relative = relative.Replace('\', PATH_DELIMITER);

        return path.TrimEnd(PATH_DELIMITER) + PATH_DELIMITER + relative.TrimStart(PATH_DELIMITER);
        }


        Source: GitHub






        share|improve this answer


























        • It looks like this might be for paths, rather than URLs.

          – Brian MacKay
          Nov 2 '15 at 18:12











        • @BrianMacKay Agreed that it looks like it, but it's from the UrlUtility class and used in the context of combining URLs

          – user3638471
          Nov 3 '15 at 19:55






        • 2





          Edited to clarify what class it belongs to

          – user3638471
          Nov 3 '15 at 19:57











        • Take care when using this Class, the rest of the class contains SharePoint specific artifacts.

          – Harry Berry
          Sep 26 '17 at 12:55



















        3














        My generic solution:



        public static string Combine(params string uriParts)
        {
        string uri = string.Empty;
        if (uriParts != null && uriParts.Any())
        {
        char trims = new char { '\', '/' };
        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);

        for (int i = 1; i < uriParts.Length; i++)
        {
        uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
        }
        }

        return uri;
        }





        share|improve this answer
























        • This helper method is very flexible and works well in many different use cases. Thank you!

          – Shiva
          May 22 '17 at 5:11



















        3














        I created this function that will make your life easier:



            /// <summary>
        /// The ultimate Path combiner of all time
        /// </summary>
        /// <param name="IsURL">
        /// true - if the paths are Internet URLs, false - if the paths are local URLs, this is very important as this will be used to decide which separator will be used.
        /// </param>
        /// <param name="IsRelative">Just adds the separator at the beginning</param>
        /// <param name="IsFixInternal">Fix the paths from within (by removing duplicate separators and correcting the separators)</param>
        /// <param name="parts">The paths to combine</param>
        /// <returns>the combined path</returns>
        public static string PathCombine(bool IsURL , bool IsRelative , bool IsFixInternal , params string parts)
        {
        if (parts == null || parts.Length == 0) return string.Empty;
        char separator = IsURL ? '/' : '\';

        if (parts.Length == 1 && IsFixInternal)
        {
        string validsingle;
        if (IsURL)
        {
        validsingle = parts[0].Replace('\' , '/');
        }
        else
        {
        validsingle = parts[0].Replace('/' , '\');
        }
        validsingle = validsingle.Trim(separator);
        return (IsRelative ? separator.ToString() : string.Empty) + validsingle;
        }

        string final = parts
        .Aggregate
        (
        (string first , string second) =>
        {
        string validfirst;
        string validsecond;
        if (IsURL)
        {
        validfirst = first.Replace('\' , '/');
        validsecond = second.Replace('\' , '/');
        }
        else
        {
        validfirst = first.Replace('/' , '\');
        validsecond = second.Replace('/' , '\');
        }
        var prefix = string.Empty;
        if (IsFixInternal)
        {
        if (IsURL)
        {
        if (validfirst.Contains("://"))
        {
        var tofix = validfirst.Substring(validfirst.IndexOf("://") + 3);
        prefix = validfirst.Replace(tofix , string.Empty).TrimStart(separator);

        var tofixlist = tofix.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

        validfirst = separator + string.Join(separator.ToString() , tofixlist);
        }
        else
        {
        var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
        validfirst = string.Join(separator.ToString() , firstlist);
        }

        var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
        validsecond = string.Join(separator.ToString() , secondlist);
        }
        else
        {
        var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
        var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

        validfirst = string.Join(separator.ToString() , firstlist);
        validsecond = string.Join(separator.ToString() , secondlist);
        }
        }
        return prefix + validfirst.Trim(separator) + separator + validsecond.Trim(separator);
        }
        );
        return (IsRelative ? separator.ToString() : string.Empty) + final;
        }


        It works for URLs as well as normal paths.



        Usage:



            // Fixes internal paths
        Console.WriteLine(PathCombine(true , true , true , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
        // Result: /folder 1/folder2/folder3/somefile.ext

        // Doesn't fix internal paths
        Console.WriteLine(PathCombine(true , true , false , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
        //result : /folder 1//////////folder2////folder3/somefile.ext

        // Don't worry about URL prefixes when fixing internal paths
        Console.WriteLine(PathCombine(true , false , true , @"///https:///lul.com///\/folder2///folder3\/" , @"/somefile.ext///"));
        // Result: https://lul.com/folder2/folder3/somefile.ext

        Console.WriteLine(PathCombine(false , true , true , @"../../../\....../../somepath" , @"anotherpath"));
        // Result: ..............somepathanotherpath





        share|improve this answer

































          3














          I find the following useful and has the following features :




          • Throws on null or white space

          • Takes multiple params parameter for multiple Url segments

          • throws on null or empty


          Class



          public static class UrlPath
          {
          private static string InternalCombine(string source, string dest)
          {
          if (string.IsNullOrWhiteSpace(source))
          throw new ArgumentException("Cannot be null or white space", nameof(source));

          if (string.IsNullOrWhiteSpace(dest))
          throw new ArgumentException("Cannot be null or white space", nameof(dest));

          return $"{source.TrimEnd('/', '\')}/{dest.TrimStart('/', '\')}";
          }

          public static string Combine(string source, params string args)
          => args.Aggregate(source, InternalCombine);
          }


          Tests



          UrlPath.Combine("test1", "test2");
          UrlPath.Combine("test1//", "test2");
          UrlPath.Combine("test1", "/test2");

          // Result = test1/test2

          UrlPath.Combine(@"test1///", @"//\\//test2", @"//\\//test3") ;

          // Result = test1/test2/test3

          UrlPath.Combine("/test1/", "/test2/", null);
          UrlPath.Combine("", "/test2/");
          UrlPath.Combine("/test1/", null);

          // Throws an ArgumentException





          share|improve this answer


























          • @PeterMortensen thanks for the edit

            – Michael Randall
            Oct 18 '18 at 23:14



















          2














          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();
          });





          share|improve this answer

































            1














            Use:



                private Uri UriCombine(string path1, string path2, string path3 = "", string path4 = "")
            {
            string path = System.IO.Path.Combine(path1, path2.TrimStart('\', '/'), path3.TrimStart('\', '/'), path4.TrimStart('\', '/'));
            string url = path.Replace('\','/');
            return new Uri(url);
            }


            It has the benefit of behaving exactly like Path.Combine.






            share|improve this answer


























            • see stackoverflow.com/a/4662962/1037948

              – drzaus
              Sep 10 '14 at 19:52





















            1














            Here is my approach and I will use it for myself too:



            public static string UrlCombine(string part1, string part2)
            {
            string newPart1 = string.Empty;
            string newPart2 = string.Empty;
            string seperator = "/";

            // If either part1 or part 2 is empty,
            // we don't need to combine with seperator
            if (string.IsNullOrEmpty(part1) || string.IsNullOrEmpty(part2))
            {
            seperator = string.Empty;
            }

            // If part1 is not empty,
            // remove '/' at last
            if (!string.IsNullOrEmpty(part1))
            {
            newPart1 = part1.TrimEnd('/');
            }

            // If part2 is not empty,
            // remove '/' at first
            if (!string.IsNullOrEmpty(part2))
            {
            newPart2 = part2.TrimStart('/');
            }

            // Now finally combine
            return string.Format("{0}{1}{2}", newPart1, seperator, newPart2);
            }





            share|improve this answer


























            • This is acceptable only for your case. There are cases which could broke your code. Also, you didn't do proper encoding of the parts of the path. This could be a huge vulnerability when it comes to cross site scripting attack.

              – Believe2014
              May 1 '14 at 15:40











            • I agree to your points. The code is supposed to do just simple combining of two url parts.

              – Amit Bhagat
              May 2 '14 at 3:14



















            1














            Use this:



            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);
            }
            }





            share|improve this answer


























            • Nice touch with 'WebPath'. :) The code might be unecessarily dense though - it's hard for me to glance at this and say, yes, that's perfect. It makes me want to see unit tests. Maybe that's just me!

              – Brian MacKay
              Dec 10 '12 at 21:42








            • 1





              x.StartsWith("/") && !x.StartsWith("http") - why the http check? what do you gain?

              – penguat
              Dec 13 '12 at 10:03











            • You don't want to try to strip off the slash if it starts with http.

              – Martin Murphy
              Apr 16 '13 at 16:12











            • @BrianMacKay, I'm not sure a two liner warrants a unit test but if you like feel free to provide one. It's not like I'm accepting patches or anything, but feel free to edit the suggestion.

              – Martin Murphy
              Apr 16 '13 at 16:23



















            1














            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);





            share|improve this answer

































              1














              Why not just use the following.



              System.IO.Path.Combine(rootUrl, subPath).Replace(@"", "/")





              share|improve this answer


























              • I was looking for the PowerShell version of this which would be: [System.IO.Path]::Combine("http://MyUrl.com/","/Images/Image.jpg")however this fails with a result of: /Images/Image.jpg. Remove the / from the second subPath and it works: [System.IO.Path]::Combine("http://MyUrl.com/","Images/Image.jpg")

                – Underverse
                Feb 6 '18 at 0:14











              • Nice idea, but it fails, when one of the parameter is null.

                – pholpar
                Mar 22 '18 at 14:19



















              0














              I used this code to solve the problem:



              string brokenBaseUrl = Context.Url.TrimEnd('/').Split('/');
              string brokenRootFolderPath = RootFolderPath.Split('/');

              for (int x = 0; x < brokenRootFolderPath.Length; x++)
              {
              //if url doesn't already contain member, append it to the end of the string with / in front
              if (!brokenBaseUrl.Contains(brokenRootFolderPath[x]))
              {
              if (x == 0)
              {
              RootLocationUrl = Context.Url.TrimEnd('/');
              }
              else
              {
              RootLocationUrl += String.Format("/{0}", brokenRootFolderPath[x]);
              }
              }
              }





              share|improve this answer

































                0














                A simple one liner:



                public static string Combine(this string uri1, string uri2) => $"{uri1.TrimEnd('/')}/{uri2.TrimStart('/')}";


                Inspired by @Matt Sharpe's answer.






                share|improve this answer































                  0














                  Well, I just concatenate two strings and use regular expressions to do the cleaning part.



                      public class UriTool
                  {
                  public static Uri Join(string path1, string path2)
                  {
                  string url = path1 + "/" + path2;
                  url = Regex.Replace(url, "(?<!http:)/{2,}", "/");

                  return new Uri(url);
                  }
                  }


                  So, you can use it like this:



                      string path1 = "http://someaddress.com/something/";
                  string path2 = "/another/address.html";
                  Uri joinedUri = UriTool.Join(path1, path2);

                  // joinedUri.ToString() returns "http://someaddress.com/something/another/address.html"





                  share|improve this answer

































                    0














                    I have combined all the previous answers:



                        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);
                    }





                    share|improve this answer





















                    • 1





                      You could have used VirtualPathUtiliy class to append and remove trailing slashes safely. Check out my answer: stackoverflow.com/a/23399048/3481183

                      – Believe2014
                      May 1 '14 at 15:38



















                    0














                    Both of these work:



                      Uri final = new Uri(Regex.Replace(baseUrl + "/" + relativePath, "(?<!http:)/{2,}", "/"));


                    Or



                      Uri final =new Uri(string.Format("{0}/{1}", baseUrl.ToString().TrimEnd('/'), relativePath.ToString().TrimStart('/')));


                    I.e. if



                    baseUrl = "http://tesrurl.test.com/Int18"


                    and



                    relativePath = "To_Folder"

                    output = http://tesrurl.test.com/Int18/To_Folder


                    Some errors will appear for the code below:



                     // If you use the below code, some issues will be there in the final URI
                    Uri final = new Uri(baseUrl, relativePath);





                    share|improve this answer

































                      0














                      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!






                      share|improve this answer





























                        1 2
                        next


                        protected by Sheridan Oct 22 '14 at 14:51



                        Thank you for your interest in this question.
                        Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                        Would you like to answer one of these unanswered questions instead?














                        32 Answers
                        32






                        active

                        oldest

                        votes








                        32 Answers
                        32






                        active

                        oldest

                        votes









                        active

                        oldest

                        votes






                        active

                        oldest

                        votes








                        1 2
                        next










                        15














                        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://foo.com/",
                        "/too/", "/many/", "/slashes/",
                        "too", "few?",
                        "x=1", "y=2"
                        // result: "http://www.foo.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






                        share|improve this answer





















                        • 3





                          Well, this question gets a lot of traffic, and the answer with 1000+ upvotes does not actually work in all cases. Years later, I actually use Flurl for this, so I am accepting this one. It seems to work in all cases I have encountered. If people don't want to take a dependency, I posted an answer that also works fine.

                          – Brian MacKay
                          Nov 28 '18 at 15:33













                        • and if you dont use Flurl and would perfer a lightweight version, github.com/jean-lourenco/UrlCombine

                          – lizzy91
                          Feb 1 at 19:59
















                        15














                        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://foo.com/",
                        "/too/", "/many/", "/slashes/",
                        "too", "few?",
                        "x=1", "y=2"
                        // result: "http://www.foo.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






                        share|improve this answer





















                        • 3





                          Well, this question gets a lot of traffic, and the answer with 1000+ upvotes does not actually work in all cases. Years later, I actually use Flurl for this, so I am accepting this one. It seems to work in all cases I have encountered. If people don't want to take a dependency, I posted an answer that also works fine.

                          – Brian MacKay
                          Nov 28 '18 at 15:33













                        • and if you dont use Flurl and would perfer a lightweight version, github.com/jean-lourenco/UrlCombine

                          – lizzy91
                          Feb 1 at 19:59














                        15












                        15








                        15







                        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://foo.com/",
                        "/too/", "/many/", "/slashes/",
                        "too", "few?",
                        "x=1", "y=2"
                        // result: "http://www.foo.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






                        share|improve this answer















                        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://foo.com/",
                        "/too/", "/many/", "/slashes/",
                        "too", "few?",
                        "x=1", "y=2"
                        // result: "http://www.foo.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







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jan 9 at 20:54

























                        answered Apr 13 '18 at 6:00









                        Michael FreidgeimMichael Freidgeim

                        13.3k689113




                        13.3k689113








                        • 3





                          Well, this question gets a lot of traffic, and the answer with 1000+ upvotes does not actually work in all cases. Years later, I actually use Flurl for this, so I am accepting this one. It seems to work in all cases I have encountered. If people don't want to take a dependency, I posted an answer that also works fine.

                          – Brian MacKay
                          Nov 28 '18 at 15:33













                        • and if you dont use Flurl and would perfer a lightweight version, github.com/jean-lourenco/UrlCombine

                          – lizzy91
                          Feb 1 at 19:59














                        • 3





                          Well, this question gets a lot of traffic, and the answer with 1000+ upvotes does not actually work in all cases. Years later, I actually use Flurl for this, so I am accepting this one. It seems to work in all cases I have encountered. If people don't want to take a dependency, I posted an answer that also works fine.

                          – Brian MacKay
                          Nov 28 '18 at 15:33













                        • and if you dont use Flurl and would perfer a lightweight version, github.com/jean-lourenco/UrlCombine

                          – lizzy91
                          Feb 1 at 19:59








                        3




                        3





                        Well, this question gets a lot of traffic, and the answer with 1000+ upvotes does not actually work in all cases. Years later, I actually use Flurl for this, so I am accepting this one. It seems to work in all cases I have encountered. If people don't want to take a dependency, I posted an answer that also works fine.

                        – Brian MacKay
                        Nov 28 '18 at 15:33







                        Well, this question gets a lot of traffic, and the answer with 1000+ upvotes does not actually work in all cases. Years later, I actually use Flurl for this, so I am accepting this one. It seems to work in all cases I have encountered. If people don't want to take a dependency, I posted an answer that also works fine.

                        – Brian MacKay
                        Nov 28 '18 at 15:33















                        and if you dont use Flurl and would perfer a lightweight version, github.com/jean-lourenco/UrlCombine

                        – lizzy91
                        Feb 1 at 19:59





                        and if you dont use Flurl and would perfer a lightweight version, github.com/jean-lourenco/UrlCombine

                        – lizzy91
                        Feb 1 at 19:59













                        1068














                        Uri has a constructor that should do this for you: new Uri(Uri baseUri, string relativeUri)



                        Here's an example:



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


                        Note from editor: Beware, this method does not work as expected. It can cut part of baseUri in some cases. See comments and other answers.






                        share|improve this answer





















                        • 332





                          I like the use of the Uri class, unfortunately it will not behave like Path.Combine as the OP asked. For example new Uri(new Uri("test.com/mydirectory/"), "/helloworld.aspx").ToString() gives you "test.com/helloworld.aspx"; which would be incorrect if we wanted a Path.Combine style result.

                          – Doctor Jones
                          Oct 28 '10 at 15:20






                        • 169





                          It's all in the slashes. If the relative path part starts with a slash, then it behaves as you described. But, if you leave the slash out, then it works the way you'd expect (note the missing slash on the second parameter): new Uri(new Uri("test.com/mydirectory/"), "helloworld.aspx").ToString() results in "test.com/mydirectory/helloworld.aspx". Path.Combine behaves similarly. If the relative path parameter starts with a slash, it only returns the relative path and doesn't combine them.

                          – Joel Beckham
                          Oct 28 '10 at 22:11








                        • 61





                          If your baseUri happened to be "test.com/mydirectory/mysubdirectory" then the result would be "test.com/mydirectory/helloworld.aspx" instead of "test.com/mydirectory/mysubdirectory/helloworld.aspx". The subtle difference is the lack of trailing slash on the first parameter. I'm all for using existing framework methods, if I have to have the trailing slash there already then I think that doing partUrl1 + partUrl2 smells a lot less - I could've potentially been chasing that trailing slash round for quite a while all for the sake of not doing string concat.

                          – Carl
                          Jan 12 '11 at 16:10






                        • 58





                          The only reason I want a URI combine method is so that I don't have to check for the trailing slash. Request.ApplicationPath is '/' if your application is at the root, but '/foo' if it's not.

                          – nickd
                          Mar 25 '11 at 16:44






                        • 19





                          I -1 this answer because this doesn't answer the problem. When you want to combine url, like when you want to use Path.Combine, you don't want to care about the trailing /. and with this, you have to care. I prefer solution of Brian MacKay or mdsharpe above

                          – Baptiste Pernet
                          Apr 21 '11 at 15:56
















                        1068














                        Uri has a constructor that should do this for you: new Uri(Uri baseUri, string relativeUri)



                        Here's an example:



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


                        Note from editor: Beware, this method does not work as expected. It can cut part of baseUri in some cases. See comments and other answers.






                        share|improve this answer





















                        • 332





                          I like the use of the Uri class, unfortunately it will not behave like Path.Combine as the OP asked. For example new Uri(new Uri("test.com/mydirectory/"), "/helloworld.aspx").ToString() gives you "test.com/helloworld.aspx"; which would be incorrect if we wanted a Path.Combine style result.

                          – Doctor Jones
                          Oct 28 '10 at 15:20






                        • 169





                          It's all in the slashes. If the relative path part starts with a slash, then it behaves as you described. But, if you leave the slash out, then it works the way you'd expect (note the missing slash on the second parameter): new Uri(new Uri("test.com/mydirectory/"), "helloworld.aspx").ToString() results in "test.com/mydirectory/helloworld.aspx". Path.Combine behaves similarly. If the relative path parameter starts with a slash, it only returns the relative path and doesn't combine them.

                          – Joel Beckham
                          Oct 28 '10 at 22:11








                        • 61





                          If your baseUri happened to be "test.com/mydirectory/mysubdirectory" then the result would be "test.com/mydirectory/helloworld.aspx" instead of "test.com/mydirectory/mysubdirectory/helloworld.aspx". The subtle difference is the lack of trailing slash on the first parameter. I'm all for using existing framework methods, if I have to have the trailing slash there already then I think that doing partUrl1 + partUrl2 smells a lot less - I could've potentially been chasing that trailing slash round for quite a while all for the sake of not doing string concat.

                          – Carl
                          Jan 12 '11 at 16:10






                        • 58





                          The only reason I want a URI combine method is so that I don't have to check for the trailing slash. Request.ApplicationPath is '/' if your application is at the root, but '/foo' if it's not.

                          – nickd
                          Mar 25 '11 at 16:44






                        • 19





                          I -1 this answer because this doesn't answer the problem. When you want to combine url, like when you want to use Path.Combine, you don't want to care about the trailing /. and with this, you have to care. I prefer solution of Brian MacKay or mdsharpe above

                          – Baptiste Pernet
                          Apr 21 '11 at 15:56














                        1068












                        1068








                        1068







                        Uri has a constructor that should do this for you: new Uri(Uri baseUri, string relativeUri)



                        Here's an example:



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


                        Note from editor: Beware, this method does not work as expected. It can cut part of baseUri in some cases. See comments and other answers.






                        share|improve this answer















                        Uri has a constructor that should do this for you: new Uri(Uri baseUri, string relativeUri)



                        Here's an example:



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


                        Note from editor: Beware, this method does not work as expected. It can cut part of baseUri in some cases. See comments and other answers.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Nov 26 '18 at 9:32









                        Karel Kral

                        3,06342631




                        3,06342631










                        answered Oct 6 '09 at 19:37









                        Joel BeckhamJoel Beckham

                        14.9k32756




                        14.9k32756








                        • 332





                          I like the use of the Uri class, unfortunately it will not behave like Path.Combine as the OP asked. For example new Uri(new Uri("test.com/mydirectory/"), "/helloworld.aspx").ToString() gives you "test.com/helloworld.aspx"; which would be incorrect if we wanted a Path.Combine style result.

                          – Doctor Jones
                          Oct 28 '10 at 15:20






                        • 169





                          It's all in the slashes. If the relative path part starts with a slash, then it behaves as you described. But, if you leave the slash out, then it works the way you'd expect (note the missing slash on the second parameter): new Uri(new Uri("test.com/mydirectory/"), "helloworld.aspx").ToString() results in "test.com/mydirectory/helloworld.aspx". Path.Combine behaves similarly. If the relative path parameter starts with a slash, it only returns the relative path and doesn't combine them.

                          – Joel Beckham
                          Oct 28 '10 at 22:11








                        • 61





                          If your baseUri happened to be "test.com/mydirectory/mysubdirectory" then the result would be "test.com/mydirectory/helloworld.aspx" instead of "test.com/mydirectory/mysubdirectory/helloworld.aspx". The subtle difference is the lack of trailing slash on the first parameter. I'm all for using existing framework methods, if I have to have the trailing slash there already then I think that doing partUrl1 + partUrl2 smells a lot less - I could've potentially been chasing that trailing slash round for quite a while all for the sake of not doing string concat.

                          – Carl
                          Jan 12 '11 at 16:10






                        • 58





                          The only reason I want a URI combine method is so that I don't have to check for the trailing slash. Request.ApplicationPath is '/' if your application is at the root, but '/foo' if it's not.

                          – nickd
                          Mar 25 '11 at 16:44






                        • 19





                          I -1 this answer because this doesn't answer the problem. When you want to combine url, like when you want to use Path.Combine, you don't want to care about the trailing /. and with this, you have to care. I prefer solution of Brian MacKay or mdsharpe above

                          – Baptiste Pernet
                          Apr 21 '11 at 15:56














                        • 332





                          I like the use of the Uri class, unfortunately it will not behave like Path.Combine as the OP asked. For example new Uri(new Uri("test.com/mydirectory/"), "/helloworld.aspx").ToString() gives you "test.com/helloworld.aspx"; which would be incorrect if we wanted a Path.Combine style result.

                          – Doctor Jones
                          Oct 28 '10 at 15:20






                        • 169





                          It's all in the slashes. If the relative path part starts with a slash, then it behaves as you described. But, if you leave the slash out, then it works the way you'd expect (note the missing slash on the second parameter): new Uri(new Uri("test.com/mydirectory/"), "helloworld.aspx").ToString() results in "test.com/mydirectory/helloworld.aspx". Path.Combine behaves similarly. If the relative path parameter starts with a slash, it only returns the relative path and doesn't combine them.

                          – Joel Beckham
                          Oct 28 '10 at 22:11








                        • 61





                          If your baseUri happened to be "test.com/mydirectory/mysubdirectory" then the result would be "test.com/mydirectory/helloworld.aspx" instead of "test.com/mydirectory/mysubdirectory/helloworld.aspx". The subtle difference is the lack of trailing slash on the first parameter. I'm all for using existing framework methods, if I have to have the trailing slash there already then I think that doing partUrl1 + partUrl2 smells a lot less - I could've potentially been chasing that trailing slash round for quite a while all for the sake of not doing string concat.

                          – Carl
                          Jan 12 '11 at 16:10






                        • 58





                          The only reason I want a URI combine method is so that I don't have to check for the trailing slash. Request.ApplicationPath is '/' if your application is at the root, but '/foo' if it's not.

                          – nickd
                          Mar 25 '11 at 16:44






                        • 19





                          I -1 this answer because this doesn't answer the problem. When you want to combine url, like when you want to use Path.Combine, you don't want to care about the trailing /. and with this, you have to care. I prefer solution of Brian MacKay or mdsharpe above

                          – Baptiste Pernet
                          Apr 21 '11 at 15:56








                        332




                        332





                        I like the use of the Uri class, unfortunately it will not behave like Path.Combine as the OP asked. For example new Uri(new Uri("test.com/mydirectory/"), "/helloworld.aspx").ToString() gives you "test.com/helloworld.aspx"; which would be incorrect if we wanted a Path.Combine style result.

                        – Doctor Jones
                        Oct 28 '10 at 15:20





                        I like the use of the Uri class, unfortunately it will not behave like Path.Combine as the OP asked. For example new Uri(new Uri("test.com/mydirectory/"), "/helloworld.aspx").ToString() gives you "test.com/helloworld.aspx"; which would be incorrect if we wanted a Path.Combine style result.

                        – Doctor Jones
                        Oct 28 '10 at 15:20




                        169




                        169





                        It's all in the slashes. If the relative path part starts with a slash, then it behaves as you described. But, if you leave the slash out, then it works the way you'd expect (note the missing slash on the second parameter): new Uri(new Uri("test.com/mydirectory/"), "helloworld.aspx").ToString() results in "test.com/mydirectory/helloworld.aspx". Path.Combine behaves similarly. If the relative path parameter starts with a slash, it only returns the relative path and doesn't combine them.

                        – Joel Beckham
                        Oct 28 '10 at 22:11







                        It's all in the slashes. If the relative path part starts with a slash, then it behaves as you described. But, if you leave the slash out, then it works the way you'd expect (note the missing slash on the second parameter): new Uri(new Uri("test.com/mydirectory/"), "helloworld.aspx").ToString() results in "test.com/mydirectory/helloworld.aspx". Path.Combine behaves similarly. If the relative path parameter starts with a slash, it only returns the relative path and doesn't combine them.

                        – Joel Beckham
                        Oct 28 '10 at 22:11






                        61




                        61





                        If your baseUri happened to be "test.com/mydirectory/mysubdirectory" then the result would be "test.com/mydirectory/helloworld.aspx" instead of "test.com/mydirectory/mysubdirectory/helloworld.aspx". The subtle difference is the lack of trailing slash on the first parameter. I'm all for using existing framework methods, if I have to have the trailing slash there already then I think that doing partUrl1 + partUrl2 smells a lot less - I could've potentially been chasing that trailing slash round for quite a while all for the sake of not doing string concat.

                        – Carl
                        Jan 12 '11 at 16:10





                        If your baseUri happened to be "test.com/mydirectory/mysubdirectory" then the result would be "test.com/mydirectory/helloworld.aspx" instead of "test.com/mydirectory/mysubdirectory/helloworld.aspx". The subtle difference is the lack of trailing slash on the first parameter. I'm all for using existing framework methods, if I have to have the trailing slash there already then I think that doing partUrl1 + partUrl2 smells a lot less - I could've potentially been chasing that trailing slash round for quite a while all for the sake of not doing string concat.

                        – Carl
                        Jan 12 '11 at 16:10




                        58




                        58





                        The only reason I want a URI combine method is so that I don't have to check for the trailing slash. Request.ApplicationPath is '/' if your application is at the root, but '/foo' if it's not.

                        – nickd
                        Mar 25 '11 at 16:44





                        The only reason I want a URI combine method is so that I don't have to check for the trailing slash. Request.ApplicationPath is '/' if your application is at the root, but '/foo' if it's not.

                        – nickd
                        Mar 25 '11 at 16:44




                        19




                        19





                        I -1 this answer because this doesn't answer the problem. When you want to combine url, like when you want to use Path.Combine, you don't want to care about the trailing /. and with this, you have to care. I prefer solution of Brian MacKay or mdsharpe above

                        – Baptiste Pernet
                        Apr 21 '11 at 15:56





                        I -1 this answer because this doesn't answer the problem. When you want to combine url, like when you want to use Path.Combine, you don't want to care about the trailing /. and with this, you have to care. I prefer solution of Brian MacKay or mdsharpe above

                        – Baptiste Pernet
                        Apr 21 '11 at 15:56











                        137














                        You use Uri.TryCreate( ... ) :



                        Uri result = null;

                        if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
                        {
                        Console.WriteLine(result);
                        }


                        Will return:




                        http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx







                        share|improve this answer



















                        • 47





                          +1: This is good, although I have an irrational problem with the output parameter. ;)

                          – Brian MacKay
                          Oct 29 '09 at 14:24






                        • 10





                          @Brian: if it helps, all TryXXX methods (int.TryParse, DateTime.TryParseExact) have this output param to make it easier to use them in an if-statement. Btw, you don't have to initialize the variable as Ryan did in this example.

                          – Abel
                          Aug 26 '10 at 22:11






                        • 31





                          This answer suffers the same problem as Joel's: joining test.com/mydirectory/ and /helloworld.aspx will result in test.com/helloworld.aspx which is seemingly not what you want.

                          – Matt Kocaj
                          Aug 27 '13 at 2:05






                        • 2





                          Hi, this failed for following : if (Uri.TryCreate(new Uri("localhost/MyService/"), "/Event/SomeMethod?abc=123", out result)) { Console.WriteLine(result); } It is showing me result as : localhost/Event/SomeMethod?abc=123 Note: "http://" is replaced from base Uri here by stackoverflow

                          – Faisal Mq
                          Nov 28 '13 at 8:45








                        • 3





                          @FaisalMq This is the correct behavior, since you passed a root-relative second parameter. If you had left out the leading / on the second parameter, you'd have gotten the result you expected.

                          – Tom Lint
                          Jan 24 '14 at 9:17
















                        137














                        You use Uri.TryCreate( ... ) :



                        Uri result = null;

                        if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
                        {
                        Console.WriteLine(result);
                        }


                        Will return:




                        http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx







                        share|improve this answer



















                        • 47





                          +1: This is good, although I have an irrational problem with the output parameter. ;)

                          – Brian MacKay
                          Oct 29 '09 at 14:24






                        • 10





                          @Brian: if it helps, all TryXXX methods (int.TryParse, DateTime.TryParseExact) have this output param to make it easier to use them in an if-statement. Btw, you don't have to initialize the variable as Ryan did in this example.

                          – Abel
                          Aug 26 '10 at 22:11






                        • 31





                          This answer suffers the same problem as Joel's: joining test.com/mydirectory/ and /helloworld.aspx will result in test.com/helloworld.aspx which is seemingly not what you want.

                          – Matt Kocaj
                          Aug 27 '13 at 2:05






                        • 2





                          Hi, this failed for following : if (Uri.TryCreate(new Uri("localhost/MyService/"), "/Event/SomeMethod?abc=123", out result)) { Console.WriteLine(result); } It is showing me result as : localhost/Event/SomeMethod?abc=123 Note: "http://" is replaced from base Uri here by stackoverflow

                          – Faisal Mq
                          Nov 28 '13 at 8:45








                        • 3





                          @FaisalMq This is the correct behavior, since you passed a root-relative second parameter. If you had left out the leading / on the second parameter, you'd have gotten the result you expected.

                          – Tom Lint
                          Jan 24 '14 at 9:17














                        137












                        137








                        137







                        You use Uri.TryCreate( ... ) :



                        Uri result = null;

                        if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
                        {
                        Console.WriteLine(result);
                        }


                        Will return:




                        http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx







                        share|improve this answer













                        You use Uri.TryCreate( ... ) :



                        Uri result = null;

                        if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
                        {
                        Console.WriteLine(result);
                        }


                        Will return:




                        http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx








                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Dec 16 '08 at 21:49









                        Ryan CookRyan Cook

                        8,19243434




                        8,19243434








                        • 47





                          +1: This is good, although I have an irrational problem with the output parameter. ;)

                          – Brian MacKay
                          Oct 29 '09 at 14:24






                        • 10





                          @Brian: if it helps, all TryXXX methods (int.TryParse, DateTime.TryParseExact) have this output param to make it easier to use them in an if-statement. Btw, you don't have to initialize the variable as Ryan did in this example.

                          – Abel
                          Aug 26 '10 at 22:11






                        • 31





                          This answer suffers the same problem as Joel's: joining test.com/mydirectory/ and /helloworld.aspx will result in test.com/helloworld.aspx which is seemingly not what you want.

                          – Matt Kocaj
                          Aug 27 '13 at 2:05






                        • 2





                          Hi, this failed for following : if (Uri.TryCreate(new Uri("localhost/MyService/"), "/Event/SomeMethod?abc=123", out result)) { Console.WriteLine(result); } It is showing me result as : localhost/Event/SomeMethod?abc=123 Note: "http://" is replaced from base Uri here by stackoverflow

                          – Faisal Mq
                          Nov 28 '13 at 8:45








                        • 3





                          @FaisalMq This is the correct behavior, since you passed a root-relative second parameter. If you had left out the leading / on the second parameter, you'd have gotten the result you expected.

                          – Tom Lint
                          Jan 24 '14 at 9:17














                        • 47





                          +1: This is good, although I have an irrational problem with the output parameter. ;)

                          – Brian MacKay
                          Oct 29 '09 at 14:24






                        • 10





                          @Brian: if it helps, all TryXXX methods (int.TryParse, DateTime.TryParseExact) have this output param to make it easier to use them in an if-statement. Btw, you don't have to initialize the variable as Ryan did in this example.

                          – Abel
                          Aug 26 '10 at 22:11






                        • 31





                          This answer suffers the same problem as Joel's: joining test.com/mydirectory/ and /helloworld.aspx will result in test.com/helloworld.aspx which is seemingly not what you want.

                          – Matt Kocaj
                          Aug 27 '13 at 2:05






                        • 2





                          Hi, this failed for following : if (Uri.TryCreate(new Uri("localhost/MyService/"), "/Event/SomeMethod?abc=123", out result)) { Console.WriteLine(result); } It is showing me result as : localhost/Event/SomeMethod?abc=123 Note: "http://" is replaced from base Uri here by stackoverflow

                          – Faisal Mq
                          Nov 28 '13 at 8:45








                        • 3





                          @FaisalMq This is the correct behavior, since you passed a root-relative second parameter. If you had left out the leading / on the second parameter, you'd have gotten the result you expected.

                          – Tom Lint
                          Jan 24 '14 at 9:17








                        47




                        47





                        +1: This is good, although I have an irrational problem with the output parameter. ;)

                        – Brian MacKay
                        Oct 29 '09 at 14:24





                        +1: This is good, although I have an irrational problem with the output parameter. ;)

                        – Brian MacKay
                        Oct 29 '09 at 14:24




                        10




                        10





                        @Brian: if it helps, all TryXXX methods (int.TryParse, DateTime.TryParseExact) have this output param to make it easier to use them in an if-statement. Btw, you don't have to initialize the variable as Ryan did in this example.

                        – Abel
                        Aug 26 '10 at 22:11





                        @Brian: if it helps, all TryXXX methods (int.TryParse, DateTime.TryParseExact) have this output param to make it easier to use them in an if-statement. Btw, you don't have to initialize the variable as Ryan did in this example.

                        – Abel
                        Aug 26 '10 at 22:11




                        31




                        31





                        This answer suffers the same problem as Joel's: joining test.com/mydirectory/ and /helloworld.aspx will result in test.com/helloworld.aspx which is seemingly not what you want.

                        – Matt Kocaj
                        Aug 27 '13 at 2:05





                        This answer suffers the same problem as Joel's: joining test.com/mydirectory/ and /helloworld.aspx will result in test.com/helloworld.aspx which is seemingly not what you want.

                        – Matt Kocaj
                        Aug 27 '13 at 2:05




                        2




                        2





                        Hi, this failed for following : if (Uri.TryCreate(new Uri("localhost/MyService/"), "/Event/SomeMethod?abc=123", out result)) { Console.WriteLine(result); } It is showing me result as : localhost/Event/SomeMethod?abc=123 Note: "http://" is replaced from base Uri here by stackoverflow

                        – Faisal Mq
                        Nov 28 '13 at 8:45







                        Hi, this failed for following : if (Uri.TryCreate(new Uri("localhost/MyService/"), "/Event/SomeMethod?abc=123", out result)) { Console.WriteLine(result); } It is showing me result as : localhost/Event/SomeMethod?abc=123 Note: "http://" is replaced from base Uri here by stackoverflow

                        – Faisal Mq
                        Nov 28 '13 at 8:45






                        3




                        3





                        @FaisalMq This is the correct behavior, since you passed a root-relative second parameter. If you had left out the leading / on the second parameter, you'd have gotten the result you expected.

                        – Tom Lint
                        Jan 24 '14 at 9:17





                        @FaisalMq This is the correct behavior, since you passed a root-relative second parameter. If you had left out the leading / on the second parameter, you'd have gotten the result you expected.

                        – Tom Lint
                        Jan 24 '14 at 9:17











                        131














                        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);
                        }





                        share|improve this answer



















                        • 7





                          +1: Although this doesn't handle relative-style paths (../../whatever.html), I like this one for its simplicity. I would also add trims for the '' character.

                          – Brian MacKay
                          May 8 '10 at 15:55






                        • 3





                          See my answer for a more fully fleshed out version of this.

                          – Brian MacKay
                          May 12 '10 at 13:46
















                        131














                        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);
                        }





                        share|improve this answer



















                        • 7





                          +1: Although this doesn't handle relative-style paths (../../whatever.html), I like this one for its simplicity. I would also add trims for the '' character.

                          – Brian MacKay
                          May 8 '10 at 15:55






                        • 3





                          See my answer for a more fully fleshed out version of this.

                          – Brian MacKay
                          May 12 '10 at 13:46














                        131












                        131








                        131







                        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);
                        }





                        share|improve this answer













                        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);
                        }






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Sep 25 '09 at 10:29









                        Matthew SharpeMatthew Sharpe

                        2,49021924




                        2,49021924








                        • 7





                          +1: Although this doesn't handle relative-style paths (../../whatever.html), I like this one for its simplicity. I would also add trims for the '' character.

                          – Brian MacKay
                          May 8 '10 at 15:55






                        • 3





                          See my answer for a more fully fleshed out version of this.

                          – Brian MacKay
                          May 12 '10 at 13:46














                        • 7





                          +1: Although this doesn't handle relative-style paths (../../whatever.html), I like this one for its simplicity. I would also add trims for the '' character.

                          – Brian MacKay
                          May 8 '10 at 15:55






                        • 3





                          See my answer for a more fully fleshed out version of this.

                          – Brian MacKay
                          May 12 '10 at 13:46








                        7




                        7





                        +1: Although this doesn't handle relative-style paths (../../whatever.html), I like this one for its simplicity. I would also add trims for the '' character.

                        – Brian MacKay
                        May 8 '10 at 15:55





                        +1: Although this doesn't handle relative-style paths (../../whatever.html), I like this one for its simplicity. I would also add trims for the '' character.

                        – Brian MacKay
                        May 8 '10 at 15:55




                        3




                        3





                        See my answer for a more fully fleshed out version of this.

                        – Brian MacKay
                        May 12 '10 at 13:46





                        See my answer for a more fully fleshed out version of this.

                        – Brian MacKay
                        May 12 '10 at 13:46











                        116














                        There's already some great answers here. Based on mdsharpe suggestion, here's an extension method that can easily be used when you want to deal with Uri instances:



                        using System;
                        using System.Linq;

                        public static class UriExtensions
                        {
                        public static Uri Append(this Uri uri, params string paths)
                        {
                        return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
                        }
                        }


                        And usage example:



                        var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;


                        This will produce http://example.com/subpath/part1/part2






                        share|improve this answer





















                        • 2





                          This solution makes it trivial to write a UriUtils.Combine("base url", "part1", "part2", ...) static method that is very similar to Path.Combine(). Nice!

                          – angularsen
                          Nov 19 '11 at 15:23











                        • To support relative URIs I had to use ToString() instead of AbsoluteUri and UriKind.AbsoluteOrRelative in the Uri constructor.

                          – angularsen
                          Nov 20 '11 at 19:34













                        • Thanks for the tip about relative Uris. Unfortunately Uri doesn't make it easy to deal with relative paths as there is always some mucking about with Request.ApplicationPath involved. Perhaps you could also try using new Uri(HttpContext.Current.Request.ApplicationPath) as a base and just call Append on it? This will give you absolute paths but should work anywhere within site structure.

                          – Ales Potocnik Hahonina
                          Nov 21 '11 at 12:03











                        • Great. Glad it helped someone else. Been using this for some time now and haven't had any issues.

                          – Ales Potocnik Hahonina
                          Jul 8 '13 at 8:58











                        • I also added check if any of paths to append are not null nor empty string.

                          – n.podbielski
                          Jan 15 '16 at 10:13
















                        116














                        There's already some great answers here. Based on mdsharpe suggestion, here's an extension method that can easily be used when you want to deal with Uri instances:



                        using System;
                        using System.Linq;

                        public static class UriExtensions
                        {
                        public static Uri Append(this Uri uri, params string paths)
                        {
                        return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
                        }
                        }


                        And usage example:



                        var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;


                        This will produce http://example.com/subpath/part1/part2






                        share|improve this answer





















                        • 2





                          This solution makes it trivial to write a UriUtils.Combine("base url", "part1", "part2", ...) static method that is very similar to Path.Combine(). Nice!

                          – angularsen
                          Nov 19 '11 at 15:23











                        • To support relative URIs I had to use ToString() instead of AbsoluteUri and UriKind.AbsoluteOrRelative in the Uri constructor.

                          – angularsen
                          Nov 20 '11 at 19:34













                        • Thanks for the tip about relative Uris. Unfortunately Uri doesn't make it easy to deal with relative paths as there is always some mucking about with Request.ApplicationPath involved. Perhaps you could also try using new Uri(HttpContext.Current.Request.ApplicationPath) as a base and just call Append on it? This will give you absolute paths but should work anywhere within site structure.

                          – Ales Potocnik Hahonina
                          Nov 21 '11 at 12:03











                        • Great. Glad it helped someone else. Been using this for some time now and haven't had any issues.

                          – Ales Potocnik Hahonina
                          Jul 8 '13 at 8:58











                        • I also added check if any of paths to append are not null nor empty string.

                          – n.podbielski
                          Jan 15 '16 at 10:13














                        116












                        116








                        116







                        There's already some great answers here. Based on mdsharpe suggestion, here's an extension method that can easily be used when you want to deal with Uri instances:



                        using System;
                        using System.Linq;

                        public static class UriExtensions
                        {
                        public static Uri Append(this Uri uri, params string paths)
                        {
                        return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
                        }
                        }


                        And usage example:



                        var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;


                        This will produce http://example.com/subpath/part1/part2






                        share|improve this answer















                        There's already some great answers here. Based on mdsharpe suggestion, here's an extension method that can easily be used when you want to deal with Uri instances:



                        using System;
                        using System.Linq;

                        public static class UriExtensions
                        {
                        public static Uri Append(this Uri uri, params string paths)
                        {
                        return new Uri(paths.Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
                        }
                        }


                        And usage example:



                        var url = new Uri("http://example.com/subpath/").Append("/part1/", "part2").AbsoluteUri;


                        This will produce http://example.com/subpath/part1/part2







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 20 '14 at 5:17









                        jdphenix

                        10.6k33260




                        10.6k33260










                        answered Nov 3 '11 at 10:20









                        Ales Potocnik HahoninaAles Potocnik Hahonina

                        2,07212230




                        2,07212230








                        • 2





                          This solution makes it trivial to write a UriUtils.Combine("base url", "part1", "part2", ...) static method that is very similar to Path.Combine(). Nice!

                          – angularsen
                          Nov 19 '11 at 15:23











                        • To support relative URIs I had to use ToString() instead of AbsoluteUri and UriKind.AbsoluteOrRelative in the Uri constructor.

                          – angularsen
                          Nov 20 '11 at 19:34













                        • Thanks for the tip about relative Uris. Unfortunately Uri doesn't make it easy to deal with relative paths as there is always some mucking about with Request.ApplicationPath involved. Perhaps you could also try using new Uri(HttpContext.Current.Request.ApplicationPath) as a base and just call Append on it? This will give you absolute paths but should work anywhere within site structure.

                          – Ales Potocnik Hahonina
                          Nov 21 '11 at 12:03











                        • Great. Glad it helped someone else. Been using this for some time now and haven't had any issues.

                          – Ales Potocnik Hahonina
                          Jul 8 '13 at 8:58











                        • I also added check if any of paths to append are not null nor empty string.

                          – n.podbielski
                          Jan 15 '16 at 10:13














                        • 2





                          This solution makes it trivial to write a UriUtils.Combine("base url", "part1", "part2", ...) static method that is very similar to Path.Combine(). Nice!

                          – angularsen
                          Nov 19 '11 at 15:23











                        • To support relative URIs I had to use ToString() instead of AbsoluteUri and UriKind.AbsoluteOrRelative in the Uri constructor.

                          – angularsen
                          Nov 20 '11 at 19:34













                        • Thanks for the tip about relative Uris. Unfortunately Uri doesn't make it easy to deal with relative paths as there is always some mucking about with Request.ApplicationPath involved. Perhaps you could also try using new Uri(HttpContext.Current.Request.ApplicationPath) as a base and just call Append on it? This will give you absolute paths but should work anywhere within site structure.

                          – Ales Potocnik Hahonina
                          Nov 21 '11 at 12:03











                        • Great. Glad it helped someone else. Been using this for some time now and haven't had any issues.

                          – Ales Potocnik Hahonina
                          Jul 8 '13 at 8:58











                        • I also added check if any of paths to append are not null nor empty string.

                          – n.podbielski
                          Jan 15 '16 at 10:13








                        2




                        2





                        This solution makes it trivial to write a UriUtils.Combine("base url", "part1", "part2", ...) static method that is very similar to Path.Combine(). Nice!

                        – angularsen
                        Nov 19 '11 at 15:23





                        This solution makes it trivial to write a UriUtils.Combine("base url", "part1", "part2", ...) static method that is very similar to Path.Combine(). Nice!

                        – angularsen
                        Nov 19 '11 at 15:23













                        To support relative URIs I had to use ToString() instead of AbsoluteUri and UriKind.AbsoluteOrRelative in the Uri constructor.

                        – angularsen
                        Nov 20 '11 at 19:34







                        To support relative URIs I had to use ToString() instead of AbsoluteUri and UriKind.AbsoluteOrRelative in the Uri constructor.

                        – angularsen
                        Nov 20 '11 at 19:34















                        Thanks for the tip about relative Uris. Unfortunately Uri doesn't make it easy to deal with relative paths as there is always some mucking about with Request.ApplicationPath involved. Perhaps you could also try using new Uri(HttpContext.Current.Request.ApplicationPath) as a base and just call Append on it? This will give you absolute paths but should work anywhere within site structure.

                        – Ales Potocnik Hahonina
                        Nov 21 '11 at 12:03





                        Thanks for the tip about relative Uris. Unfortunately Uri doesn't make it easy to deal with relative paths as there is always some mucking about with Request.ApplicationPath involved. Perhaps you could also try using new Uri(HttpContext.Current.Request.ApplicationPath) as a base and just call Append on it? This will give you absolute paths but should work anywhere within site structure.

                        – Ales Potocnik Hahonina
                        Nov 21 '11 at 12:03













                        Great. Glad it helped someone else. Been using this for some time now and haven't had any issues.

                        – Ales Potocnik Hahonina
                        Jul 8 '13 at 8:58





                        Great. Glad it helped someone else. Been using this for some time now and haven't had any issues.

                        – Ales Potocnik Hahonina
                        Jul 8 '13 at 8:58













                        I also added check if any of paths to append are not null nor empty string.

                        – n.podbielski
                        Jan 15 '16 at 10:13





                        I also added check if any of paths to append are not null nor empty string.

                        – n.podbielski
                        Jan 15 '16 at 10:13











                        82














                        Ryan Cook's answer is close to what I'm after and may be more appropriate for other developers. However, it adds http:// to the beginning of the string and in general it does a bit more formatting than I'm after.



                        Also, for my use cases, resolving relative paths is not important.



                        mdsharp's answer also contains the seed of a good idea, although that actual implementation needed a few more details to be complete. This is an attempt to flesh it out (and I'm using this in production):



                        C#



                        public string UrlCombine(string url1, string url2)
                        {
                        if (url1.Length == 0) {
                        return url2;
                        }

                        if (url2.Length == 0) {
                        return url1;
                        }

                        url1 = url1.TrimEnd('/', '\');
                        url2 = url2.TrimStart('/', '\');

                        return string.Format("{0}/{1}", url1, url2);
                        }


                        VB.NET



                        Public Function UrlCombine(ByVal url1 As String, ByVal url2 As String) As String
                        If url1.Length = 0 Then
                        Return url2
                        End If

                        If url2.Length = 0 Then
                        Return url1
                        End If

                        url1 = url1.TrimEnd("/"c, ""c)
                        url2 = url2.TrimStart("/"c, ""c)

                        Return String.Format("{0}/{1}", url1, url2)
                        End Function


                        This code passes the following test, which happens to be in VB:



                        <TestMethod()> Public Sub UrlCombineTest()
                        Dim target As StringHelpers = New StringHelpers()

                        Assert.IsTrue(target.UrlCombine("test1", "test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1/", "test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1", "/test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1/", "/test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("/test1/", "/test2/") = "/test1/test2/")
                        Assert.IsTrue(target.UrlCombine("", "/test2/") = "/test2/")
                        Assert.IsTrue(target.UrlCombine("/test1/", "") = "/test1/")
                        End Sub





                        share|improve this answer





















                        • 4





                          Talking of details: what about the mandatory ArgumentNullException("url1") if the argument is Nothing? Sorry, just being picky ;-). Note that a backslash has nothing to do in a URI (and if it is there, it should not be trimmed), so you can remove that from your TrimXXX.

                          – Abel
                          Aug 26 '10 at 22:21






                        • 4





                          you can use params string and recursively join them to allow more than 2 combinations

                          – Jaider
                          Jun 12 '12 at 22:47






                        • 4





                          I sure wish this was in the Base Class Library like Path.Combine.

                          – Uriah Blatherwick
                          Aug 18 '14 at 18:30






                        • 1





                          @MarkHurd I edited the code again, so that it's behaviorally the same as the C#, and syntactically equivalent as well.

                          – JJS
                          Jul 7 '16 at 19:23






                        • 1





                          @BrianMacKay i broke it, markhurd pointed out my mistake and rolled back, i updated again... cheers

                          – JJS
                          Jul 11 '16 at 13:28
















                        82














                        Ryan Cook's answer is close to what I'm after and may be more appropriate for other developers. However, it adds http:// to the beginning of the string and in general it does a bit more formatting than I'm after.



                        Also, for my use cases, resolving relative paths is not important.



                        mdsharp's answer also contains the seed of a good idea, although that actual implementation needed a few more details to be complete. This is an attempt to flesh it out (and I'm using this in production):



                        C#



                        public string UrlCombine(string url1, string url2)
                        {
                        if (url1.Length == 0) {
                        return url2;
                        }

                        if (url2.Length == 0) {
                        return url1;
                        }

                        url1 = url1.TrimEnd('/', '\');
                        url2 = url2.TrimStart('/', '\');

                        return string.Format("{0}/{1}", url1, url2);
                        }


                        VB.NET



                        Public Function UrlCombine(ByVal url1 As String, ByVal url2 As String) As String
                        If url1.Length = 0 Then
                        Return url2
                        End If

                        If url2.Length = 0 Then
                        Return url1
                        End If

                        url1 = url1.TrimEnd("/"c, ""c)
                        url2 = url2.TrimStart("/"c, ""c)

                        Return String.Format("{0}/{1}", url1, url2)
                        End Function


                        This code passes the following test, which happens to be in VB:



                        <TestMethod()> Public Sub UrlCombineTest()
                        Dim target As StringHelpers = New StringHelpers()

                        Assert.IsTrue(target.UrlCombine("test1", "test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1/", "test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1", "/test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1/", "/test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("/test1/", "/test2/") = "/test1/test2/")
                        Assert.IsTrue(target.UrlCombine("", "/test2/") = "/test2/")
                        Assert.IsTrue(target.UrlCombine("/test1/", "") = "/test1/")
                        End Sub





                        share|improve this answer





















                        • 4





                          Talking of details: what about the mandatory ArgumentNullException("url1") if the argument is Nothing? Sorry, just being picky ;-). Note that a backslash has nothing to do in a URI (and if it is there, it should not be trimmed), so you can remove that from your TrimXXX.

                          – Abel
                          Aug 26 '10 at 22:21






                        • 4





                          you can use params string and recursively join them to allow more than 2 combinations

                          – Jaider
                          Jun 12 '12 at 22:47






                        • 4





                          I sure wish this was in the Base Class Library like Path.Combine.

                          – Uriah Blatherwick
                          Aug 18 '14 at 18:30






                        • 1





                          @MarkHurd I edited the code again, so that it's behaviorally the same as the C#, and syntactically equivalent as well.

                          – JJS
                          Jul 7 '16 at 19:23






                        • 1





                          @BrianMacKay i broke it, markhurd pointed out my mistake and rolled back, i updated again... cheers

                          – JJS
                          Jul 11 '16 at 13:28














                        82












                        82








                        82







                        Ryan Cook's answer is close to what I'm after and may be more appropriate for other developers. However, it adds http:// to the beginning of the string and in general it does a bit more formatting than I'm after.



                        Also, for my use cases, resolving relative paths is not important.



                        mdsharp's answer also contains the seed of a good idea, although that actual implementation needed a few more details to be complete. This is an attempt to flesh it out (and I'm using this in production):



                        C#



                        public string UrlCombine(string url1, string url2)
                        {
                        if (url1.Length == 0) {
                        return url2;
                        }

                        if (url2.Length == 0) {
                        return url1;
                        }

                        url1 = url1.TrimEnd('/', '\');
                        url2 = url2.TrimStart('/', '\');

                        return string.Format("{0}/{1}", url1, url2);
                        }


                        VB.NET



                        Public Function UrlCombine(ByVal url1 As String, ByVal url2 As String) As String
                        If url1.Length = 0 Then
                        Return url2
                        End If

                        If url2.Length = 0 Then
                        Return url1
                        End If

                        url1 = url1.TrimEnd("/"c, ""c)
                        url2 = url2.TrimStart("/"c, ""c)

                        Return String.Format("{0}/{1}", url1, url2)
                        End Function


                        This code passes the following test, which happens to be in VB:



                        <TestMethod()> Public Sub UrlCombineTest()
                        Dim target As StringHelpers = New StringHelpers()

                        Assert.IsTrue(target.UrlCombine("test1", "test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1/", "test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1", "/test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1/", "/test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("/test1/", "/test2/") = "/test1/test2/")
                        Assert.IsTrue(target.UrlCombine("", "/test2/") = "/test2/")
                        Assert.IsTrue(target.UrlCombine("/test1/", "") = "/test1/")
                        End Sub





                        share|improve this answer















                        Ryan Cook's answer is close to what I'm after and may be more appropriate for other developers. However, it adds http:// to the beginning of the string and in general it does a bit more formatting than I'm after.



                        Also, for my use cases, resolving relative paths is not important.



                        mdsharp's answer also contains the seed of a good idea, although that actual implementation needed a few more details to be complete. This is an attempt to flesh it out (and I'm using this in production):



                        C#



                        public string UrlCombine(string url1, string url2)
                        {
                        if (url1.Length == 0) {
                        return url2;
                        }

                        if (url2.Length == 0) {
                        return url1;
                        }

                        url1 = url1.TrimEnd('/', '\');
                        url2 = url2.TrimStart('/', '\');

                        return string.Format("{0}/{1}", url1, url2);
                        }


                        VB.NET



                        Public Function UrlCombine(ByVal url1 As String, ByVal url2 As String) As String
                        If url1.Length = 0 Then
                        Return url2
                        End If

                        If url2.Length = 0 Then
                        Return url1
                        End If

                        url1 = url1.TrimEnd("/"c, ""c)
                        url2 = url2.TrimStart("/"c, ""c)

                        Return String.Format("{0}/{1}", url1, url2)
                        End Function


                        This code passes the following test, which happens to be in VB:



                        <TestMethod()> Public Sub UrlCombineTest()
                        Dim target As StringHelpers = New StringHelpers()

                        Assert.IsTrue(target.UrlCombine("test1", "test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1/", "test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1", "/test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("test1/", "/test2") = "test1/test2")
                        Assert.IsTrue(target.UrlCombine("/test1/", "/test2/") = "/test1/test2/")
                        Assert.IsTrue(target.UrlCombine("", "/test2/") = "/test2/")
                        Assert.IsTrue(target.UrlCombine("/test1/", "") = "/test1/")
                        End Sub






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Oct 18 '18 at 20:01









                        Peter Mortensen

                        13.8k1987113




                        13.8k1987113










                        answered May 10 '10 at 21:53









                        Brian MacKayBrian MacKay

                        17.2k1370109




                        17.2k1370109








                        • 4





                          Talking of details: what about the mandatory ArgumentNullException("url1") if the argument is Nothing? Sorry, just being picky ;-). Note that a backslash has nothing to do in a URI (and if it is there, it should not be trimmed), so you can remove that from your TrimXXX.

                          – Abel
                          Aug 26 '10 at 22:21






                        • 4





                          you can use params string and recursively join them to allow more than 2 combinations

                          – Jaider
                          Jun 12 '12 at 22:47






                        • 4





                          I sure wish this was in the Base Class Library like Path.Combine.

                          – Uriah Blatherwick
                          Aug 18 '14 at 18:30






                        • 1





                          @MarkHurd I edited the code again, so that it's behaviorally the same as the C#, and syntactically equivalent as well.

                          – JJS
                          Jul 7 '16 at 19:23






                        • 1





                          @BrianMacKay i broke it, markhurd pointed out my mistake and rolled back, i updated again... cheers

                          – JJS
                          Jul 11 '16 at 13:28














                        • 4





                          Talking of details: what about the mandatory ArgumentNullException("url1") if the argument is Nothing? Sorry, just being picky ;-). Note that a backslash has nothing to do in a URI (and if it is there, it should not be trimmed), so you can remove that from your TrimXXX.

                          – Abel
                          Aug 26 '10 at 22:21






                        • 4





                          you can use params string and recursively join them to allow more than 2 combinations

                          – Jaider
                          Jun 12 '12 at 22:47






                        • 4





                          I sure wish this was in the Base Class Library like Path.Combine.

                          – Uriah Blatherwick
                          Aug 18 '14 at 18:30






                        • 1





                          @MarkHurd I edited the code again, so that it's behaviorally the same as the C#, and syntactically equivalent as well.

                          – JJS
                          Jul 7 '16 at 19:23






                        • 1





                          @BrianMacKay i broke it, markhurd pointed out my mistake and rolled back, i updated again... cheers

                          – JJS
                          Jul 11 '16 at 13:28








                        4




                        4





                        Talking of details: what about the mandatory ArgumentNullException("url1") if the argument is Nothing? Sorry, just being picky ;-). Note that a backslash has nothing to do in a URI (and if it is there, it should not be trimmed), so you can remove that from your TrimXXX.

                        – Abel
                        Aug 26 '10 at 22:21





                        Talking of details: what about the mandatory ArgumentNullException("url1") if the argument is Nothing? Sorry, just being picky ;-). Note that a backslash has nothing to do in a URI (and if it is there, it should not be trimmed), so you can remove that from your TrimXXX.

                        – Abel
                        Aug 26 '10 at 22:21




                        4




                        4





                        you can use params string and recursively join them to allow more than 2 combinations

                        – Jaider
                        Jun 12 '12 at 22:47





                        you can use params string and recursively join them to allow more than 2 combinations

                        – Jaider
                        Jun 12 '12 at 22:47




                        4




                        4





                        I sure wish this was in the Base Class Library like Path.Combine.

                        – Uriah Blatherwick
                        Aug 18 '14 at 18:30





                        I sure wish this was in the Base Class Library like Path.Combine.

                        – Uriah Blatherwick
                        Aug 18 '14 at 18:30




                        1




                        1





                        @MarkHurd I edited the code again, so that it's behaviorally the same as the C#, and syntactically equivalent as well.

                        – JJS
                        Jul 7 '16 at 19:23





                        @MarkHurd I edited the code again, so that it's behaviorally the same as the C#, and syntactically equivalent as well.

                        – JJS
                        Jul 7 '16 at 19:23




                        1




                        1





                        @BrianMacKay i broke it, markhurd pointed out my mistake and rolled back, i updated again... cheers

                        – JJS
                        Jul 11 '16 at 13:28





                        @BrianMacKay i broke it, markhurd pointed out my mistake and rolled back, i updated again... cheers

                        – JJS
                        Jul 11 '16 at 13:28











                        32














                        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");).






                        share|improve this answer


























                        • +1 because it's close to what I'm looking for, although it would be ideal if it would work for any old url. I double it will get much more elegant than what mdsharpe proposed.

                          – Brian MacKay
                          Mar 29 '10 at 21:28






                        • 2





                          The caveat is correct, it cannot work with absolute uris and the result is always relative from the root. But it has an added benefit, it processes the tilde, as with "~/". This makes it a shortcut for Server.MapPath and combining.

                          – Abel
                          Aug 26 '10 at 22:18


















                        32














                        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");).






                        share|improve this answer


























                        • +1 because it's close to what I'm looking for, although it would be ideal if it would work for any old url. I double it will get much more elegant than what mdsharpe proposed.

                          – Brian MacKay
                          Mar 29 '10 at 21:28






                        • 2





                          The caveat is correct, it cannot work with absolute uris and the result is always relative from the root. But it has an added benefit, it processes the tilde, as with "~/". This makes it a shortcut for Server.MapPath and combining.

                          – Abel
                          Aug 26 '10 at 22:18
















                        32












                        32








                        32







                        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");).






                        share|improve this answer















                        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");).







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Sep 20 '18 at 9:05









                        Kolappan Nathan

                        56011320




                        56011320










                        answered Mar 28 '10 at 0:21









                        Jeronimo Colon IIIJeronimo Colon III

                        52156




                        52156













                        • +1 because it's close to what I'm looking for, although it would be ideal if it would work for any old url. I double it will get much more elegant than what mdsharpe proposed.

                          – Brian MacKay
                          Mar 29 '10 at 21:28






                        • 2





                          The caveat is correct, it cannot work with absolute uris and the result is always relative from the root. But it has an added benefit, it processes the tilde, as with "~/". This makes it a shortcut for Server.MapPath and combining.

                          – Abel
                          Aug 26 '10 at 22:18





















                        • +1 because it's close to what I'm looking for, although it would be ideal if it would work for any old url. I double it will get much more elegant than what mdsharpe proposed.

                          – Brian MacKay
                          Mar 29 '10 at 21:28






                        • 2





                          The caveat is correct, it cannot work with absolute uris and the result is always relative from the root. But it has an added benefit, it processes the tilde, as with "~/". This makes it a shortcut for Server.MapPath and combining.

                          – Abel
                          Aug 26 '10 at 22:18



















                        +1 because it's close to what I'm looking for, although it would be ideal if it would work for any old url. I double it will get much more elegant than what mdsharpe proposed.

                        – Brian MacKay
                        Mar 29 '10 at 21:28





                        +1 because it's close to what I'm looking for, although it would be ideal if it would work for any old url. I double it will get much more elegant than what mdsharpe proposed.

                        – Brian MacKay
                        Mar 29 '10 at 21:28




                        2




                        2





                        The caveat is correct, it cannot work with absolute uris and the result is always relative from the root. But it has an added benefit, it processes the tilde, as with "~/". This makes it a shortcut for Server.MapPath and combining.

                        – Abel
                        Aug 26 '10 at 22:18







                        The caveat is correct, it cannot work with absolute uris and the result is always relative from the root. But it has an added benefit, it processes the tilde, as with "~/". This makes it a shortcut for Server.MapPath and combining.

                        – Abel
                        Aug 26 '10 at 22:18













                        29














                        Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.



                        I first tried the new Uri(Uri baseUri, string relativeUri) approach, which failed for me because of URIs like http://www.mediawiki.org/wiki/Special:SpecialPages:



                        new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")


                        will result in Special:SpecialPages, because of the colon after Special that denotes a scheme.



                        So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:



                        public static string CombineUri(params string uriParts)
                        {
                        string uri = string.Empty;
                        if (uriParts != null && uriParts.Count() > 0)
                        {
                        char trims = new char { '\', '/' };
                        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
                        for (int i = 1; i < uriParts.Count(); i++)
                        {
                        uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
                        }
                        }
                        return uri;
                        }


                        Usage: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")






                        share|improve this answer





















                        • 1





                          +1: Now we're talking... I'm going to try this out. This might even end up being the new accepted answer. After trying to new Uri() method I really don't like it. Too finnicky.

                          – Brian MacKay
                          Jul 18 '11 at 14:23











                        • This is exactly what I needed! Was not a fan of having to care where I put trailing slashes, etc...

                          – Gromer
                          Aug 6 '12 at 21:52











                        • +1 for rolling in the null checking so it won't blow up.

                          – NightOwl888
                          Mar 6 '14 at 13:34
















                        29














                        Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.



                        I first tried the new Uri(Uri baseUri, string relativeUri) approach, which failed for me because of URIs like http://www.mediawiki.org/wiki/Special:SpecialPages:



                        new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")


                        will result in Special:SpecialPages, because of the colon after Special that denotes a scheme.



                        So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:



                        public static string CombineUri(params string uriParts)
                        {
                        string uri = string.Empty;
                        if (uriParts != null && uriParts.Count() > 0)
                        {
                        char trims = new char { '\', '/' };
                        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
                        for (int i = 1; i < uriParts.Count(); i++)
                        {
                        uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
                        }
                        }
                        return uri;
                        }


                        Usage: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")






                        share|improve this answer





















                        • 1





                          +1: Now we're talking... I'm going to try this out. This might even end up being the new accepted answer. After trying to new Uri() method I really don't like it. Too finnicky.

                          – Brian MacKay
                          Jul 18 '11 at 14:23











                        • This is exactly what I needed! Was not a fan of having to care where I put trailing slashes, etc...

                          – Gromer
                          Aug 6 '12 at 21:52











                        • +1 for rolling in the null checking so it won't blow up.

                          – NightOwl888
                          Mar 6 '14 at 13:34














                        29












                        29








                        29







                        Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.



                        I first tried the new Uri(Uri baseUri, string relativeUri) approach, which failed for me because of URIs like http://www.mediawiki.org/wiki/Special:SpecialPages:



                        new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")


                        will result in Special:SpecialPages, because of the colon after Special that denotes a scheme.



                        So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:



                        public static string CombineUri(params string uriParts)
                        {
                        string uri = string.Empty;
                        if (uriParts != null && uriParts.Count() > 0)
                        {
                        char trims = new char { '\', '/' };
                        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
                        for (int i = 1; i < uriParts.Count(); i++)
                        {
                        uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
                        }
                        }
                        return uri;
                        }


                        Usage: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")






                        share|improve this answer















                        Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.



                        I first tried the new Uri(Uri baseUri, string relativeUri) approach, which failed for me because of URIs like http://www.mediawiki.org/wiki/Special:SpecialPages:



                        new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")


                        will result in Special:SpecialPages, because of the colon after Special that denotes a scheme.



                        So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:



                        public static string CombineUri(params string uriParts)
                        {
                        string uri = string.Empty;
                        if (uriParts != null && uriParts.Count() > 0)
                        {
                        char trims = new char { '\', '/' };
                        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
                        for (int i = 1; i < uriParts.Count(); i++)
                        {
                        uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
                        }
                        }
                        return uri;
                        }


                        Usage: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Oct 18 '18 at 19:58









                        Peter Mortensen

                        13.8k1987113




                        13.8k1987113










                        answered Jul 15 '11 at 8:17









                        Mike FuchsMike Fuchs

                        9,85024261




                        9,85024261








                        • 1





                          +1: Now we're talking... I'm going to try this out. This might even end up being the new accepted answer. After trying to new Uri() method I really don't like it. Too finnicky.

                          – Brian MacKay
                          Jul 18 '11 at 14:23











                        • This is exactly what I needed! Was not a fan of having to care where I put trailing slashes, etc...

                          – Gromer
                          Aug 6 '12 at 21:52











                        • +1 for rolling in the null checking so it won't blow up.

                          – NightOwl888
                          Mar 6 '14 at 13:34














                        • 1





                          +1: Now we're talking... I'm going to try this out. This might even end up being the new accepted answer. After trying to new Uri() method I really don't like it. Too finnicky.

                          – Brian MacKay
                          Jul 18 '11 at 14:23











                        • This is exactly what I needed! Was not a fan of having to care where I put trailing slashes, etc...

                          – Gromer
                          Aug 6 '12 at 21:52











                        • +1 for rolling in the null checking so it won't blow up.

                          – NightOwl888
                          Mar 6 '14 at 13:34








                        1




                        1





                        +1: Now we're talking... I'm going to try this out. This might even end up being the new accepted answer. After trying to new Uri() method I really don't like it. Too finnicky.

                        – Brian MacKay
                        Jul 18 '11 at 14:23





                        +1: Now we're talking... I'm going to try this out. This might even end up being the new accepted answer. After trying to new Uri() method I really don't like it. Too finnicky.

                        – Brian MacKay
                        Jul 18 '11 at 14:23













                        This is exactly what I needed! Was not a fan of having to care where I put trailing slashes, etc...

                        – Gromer
                        Aug 6 '12 at 21:52





                        This is exactly what I needed! Was not a fan of having to care where I put trailing slashes, etc...

                        – Gromer
                        Aug 6 '12 at 21:52













                        +1 for rolling in the null checking so it won't blow up.

                        – NightOwl888
                        Mar 6 '14 at 13:34





                        +1 for rolling in the null checking so it won't blow up.

                        – NightOwl888
                        Mar 6 '14 at 13:34











                        22














                        Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\", "/")





                        share|improve this answer



















                        • 7





                          path.Replace(Path.DirectorySeparatorChar, '/');

                          – Jaider
                          Jun 12 '12 at 22:51






                        • 4





                          path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)

                          – SliverNinja - MSFT
                          Aug 16 '12 at 14:31








                        • 1





                          To get it to wrk u must remove first / in second arg ie "/Images" - / Path.Combine("Http://MyUrl.com", "Images/Image.jpg")

                          – Per G
                          Apr 25 '13 at 10:43








                        • 7





                          @SliverNinja That's not correct The value of this field is a backslash ('') on UNIX, and a slash ('/') on Windows and Macintosh operating systems. When using Mono on a Linux system, you'd get the wrong separator.

                          – Stijn
                          Mar 13 '14 at 10:01






                        • 3





                          All yall that are geeking out on the Directory Separator are forgetting that the strings could have come from a different OS than you are on now. Just replace backslash with forward slash and you're covered.

                          – JeremyWeir
                          Jul 26 '16 at 22:43
















                        22














                        Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\", "/")





                        share|improve this answer



















                        • 7





                          path.Replace(Path.DirectorySeparatorChar, '/');

                          – Jaider
                          Jun 12 '12 at 22:51






                        • 4





                          path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)

                          – SliverNinja - MSFT
                          Aug 16 '12 at 14:31








                        • 1





                          To get it to wrk u must remove first / in second arg ie "/Images" - / Path.Combine("Http://MyUrl.com", "Images/Image.jpg")

                          – Per G
                          Apr 25 '13 at 10:43








                        • 7





                          @SliverNinja That's not correct The value of this field is a backslash ('') on UNIX, and a slash ('/') on Windows and Macintosh operating systems. When using Mono on a Linux system, you'd get the wrong separator.

                          – Stijn
                          Mar 13 '14 at 10:01






                        • 3





                          All yall that are geeking out on the Directory Separator are forgetting that the strings could have come from a different OS than you are on now. Just replace backslash with forward slash and you're covered.

                          – JeremyWeir
                          Jul 26 '16 at 22:43














                        22












                        22








                        22







                        Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\", "/")





                        share|improve this answer













                        Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\", "/")






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 11 '11 at 21:41









                        JeremyWeirJeremyWeir

                        18.2k976101




                        18.2k976101








                        • 7





                          path.Replace(Path.DirectorySeparatorChar, '/');

                          – Jaider
                          Jun 12 '12 at 22:51






                        • 4





                          path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)

                          – SliverNinja - MSFT
                          Aug 16 '12 at 14:31








                        • 1





                          To get it to wrk u must remove first / in second arg ie "/Images" - / Path.Combine("Http://MyUrl.com", "Images/Image.jpg")

                          – Per G
                          Apr 25 '13 at 10:43








                        • 7





                          @SliverNinja That's not correct The value of this field is a backslash ('') on UNIX, and a slash ('/') on Windows and Macintosh operating systems. When using Mono on a Linux system, you'd get the wrong separator.

                          – Stijn
                          Mar 13 '14 at 10:01






                        • 3





                          All yall that are geeking out on the Directory Separator are forgetting that the strings could have come from a different OS than you are on now. Just replace backslash with forward slash and you're covered.

                          – JeremyWeir
                          Jul 26 '16 at 22:43














                        • 7





                          path.Replace(Path.DirectorySeparatorChar, '/');

                          – Jaider
                          Jun 12 '12 at 22:51






                        • 4





                          path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)

                          – SliverNinja - MSFT
                          Aug 16 '12 at 14:31








                        • 1





                          To get it to wrk u must remove first / in second arg ie "/Images" - / Path.Combine("Http://MyUrl.com", "Images/Image.jpg")

                          – Per G
                          Apr 25 '13 at 10:43








                        • 7





                          @SliverNinja That's not correct The value of this field is a backslash ('') on UNIX, and a slash ('/') on Windows and Macintosh operating systems. When using Mono on a Linux system, you'd get the wrong separator.

                          – Stijn
                          Mar 13 '14 at 10:01






                        • 3





                          All yall that are geeking out on the Directory Separator are forgetting that the strings could have come from a different OS than you are on now. Just replace backslash with forward slash and you're covered.

                          – JeremyWeir
                          Jul 26 '16 at 22:43








                        7




                        7





                        path.Replace(Path.DirectorySeparatorChar, '/');

                        – Jaider
                        Jun 12 '12 at 22:51





                        path.Replace(Path.DirectorySeparatorChar, '/');

                        – Jaider
                        Jun 12 '12 at 22:51




                        4




                        4





                        path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)

                        – SliverNinja - MSFT
                        Aug 16 '12 at 14:31







                        path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)

                        – SliverNinja - MSFT
                        Aug 16 '12 at 14:31






                        1




                        1





                        To get it to wrk u must remove first / in second arg ie "/Images" - / Path.Combine("Http://MyUrl.com", "Images/Image.jpg")

                        – Per G
                        Apr 25 '13 at 10:43







                        To get it to wrk u must remove first / in second arg ie "/Images" - / Path.Combine("Http://MyUrl.com", "Images/Image.jpg")

                        – Per G
                        Apr 25 '13 at 10:43






                        7




                        7





                        @SliverNinja That's not correct The value of this field is a backslash ('') on UNIX, and a slash ('/') on Windows and Macintosh operating systems. When using Mono on a Linux system, you'd get the wrong separator.

                        – Stijn
                        Mar 13 '14 at 10:01





                        @SliverNinja That's not correct The value of this field is a backslash ('') on UNIX, and a slash ('/') on Windows and Macintosh operating systems. When using Mono on a Linux system, you'd get the wrong separator.

                        – Stijn
                        Mar 13 '14 at 10:01




                        3




                        3





                        All yall that are geeking out on the Directory Separator are forgetting that the strings could have come from a different OS than you are on now. Just replace backslash with forward slash and you're covered.

                        – JeremyWeir
                        Jul 26 '16 at 22:43





                        All yall that are geeking out on the Directory Separator are forgetting that the strings could have come from a different OS than you are on now. Just replace backslash with forward slash and you're covered.

                        – JeremyWeir
                        Jul 26 '16 at 22:43











                        16














                        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");





                        share|improve this answer






























                          16














                          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");





                          share|improve this answer




























                            16












                            16








                            16







                            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");





                            share|improve this answer















                            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");






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Oct 18 '18 at 19:59









                            Peter Mortensen

                            13.8k1987113




                            13.8k1987113










                            answered Nov 25 '10 at 8:43









                            urzaurza

                            17712




                            17712























                                11














                                Witty example, Ryan, to end with a link to the function. Well done.



                                One recommendation Brian: if you wrap this code in a function, you may want to use a UriBuilder to wrap the base URL prior to the TryCreate call.



                                Otherwise, the base URL MUST include the scheme (where the UriBuilder will assume http://). Just a thought:



                                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");
                                }





                                share|improve this answer






























                                  11














                                  Witty example, Ryan, to end with a link to the function. Well done.



                                  One recommendation Brian: if you wrap this code in a function, you may want to use a UriBuilder to wrap the base URL prior to the TryCreate call.



                                  Otherwise, the base URL MUST include the scheme (where the UriBuilder will assume http://). Just a thought:



                                  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");
                                  }





                                  share|improve this answer




























                                    11












                                    11








                                    11







                                    Witty example, Ryan, to end with a link to the function. Well done.



                                    One recommendation Brian: if you wrap this code in a function, you may want to use a UriBuilder to wrap the base URL prior to the TryCreate call.



                                    Otherwise, the base URL MUST include the scheme (where the UriBuilder will assume http://). Just a thought:



                                    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");
                                    }





                                    share|improve this answer















                                    Witty example, Ryan, to end with a link to the function. Well done.



                                    One recommendation Brian: if you wrap this code in a function, you may want to use a UriBuilder to wrap the base URL prior to the TryCreate call.



                                    Otherwise, the base URL MUST include the scheme (where the UriBuilder will assume http://). Just a thought:



                                    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");
                                    }






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Feb 3 '15 at 15:04









                                    Peter Mortensen

                                    13.8k1987113




                                    13.8k1987113










                                    answered Jul 30 '09 at 15:08









                                    mtazvamtazva

                                    897713




                                    897713























                                        8














                                        Combining multiple parts of a URL could be a little bit tricky. You can use the two-parameter constructor Uri(baseUri, relativeUri), or you can use the Uri.TryCreate() utility function.



                                        In either case, you might end up returning an incorrect result because these methods keep on truncating the relative parts off of the first parameter baseUri, i.e. from something like http://google.com/some/thing to http://google.com.



                                        To be able to combine multiple parts into a final URL, you can copy the two functions below:



                                            public static string Combine(params string parts)
                                        {
                                        if (parts == null || parts.Length == 0) return string.Empty;

                                        var urlBuilder = new StringBuilder();
                                        foreach (var part in parts)
                                        {
                                        var tempUrl = tryCreateRelativeOrAbsolute(part);
                                        urlBuilder.Append(tempUrl);
                                        }
                                        return VirtualPathUtility.RemoveTrailingSlash(urlBuilder.ToString());
                                        }

                                        private static string tryCreateRelativeOrAbsolute(string s)
                                        {
                                        System.Uri uri;
                                        System.Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri);
                                        string tempUrl = VirtualPathUtility.AppendTrailingSlash(uri.ToString());
                                        return tempUrl;
                                        }


                                        Full code with unit tests to demonstrate usage can be found at https://uricombine.codeplex.com/SourceControl/latest#UriCombine/Uri.cs



                                        I have unit tests to cover the three most common cases:



                                        Enter image description here






                                        share|improve this answer





















                                        • 1





                                          Looks pretty good to me. Although you could replace the I loop with a foreach loop for better clarity.

                                          – Chris Marisic
                                          May 1 '14 at 18:55











                                        • Thanks Chris. I have just changed my code to use Foreach.

                                          – Believe2014
                                          May 2 '14 at 4:03






                                        • 1





                                          +1 for all the extra effort. I need to maintain this question a bit for some of the higher voted answers, you have thrown down the gauntlet. ;)

                                          – Brian MacKay
                                          May 4 '14 at 11:42













                                        • Sorry, but not enough. Works in the few cases you show but far from being usable in al combinations. For instance, colons in the path will cause harm.

                                          – Gábor
                                          May 13 '18 at 20:43











                                        • Can you please give an example of what you mean? I will be happy to fix the issue and help the next users.

                                          – Believe2014
                                          May 14 '18 at 21:23
















                                        8














                                        Combining multiple parts of a URL could be a little bit tricky. You can use the two-parameter constructor Uri(baseUri, relativeUri), or you can use the Uri.TryCreate() utility function.



                                        In either case, you might end up returning an incorrect result because these methods keep on truncating the relative parts off of the first parameter baseUri, i.e. from something like http://google.com/some/thing to http://google.com.



                                        To be able to combine multiple parts into a final URL, you can copy the two functions below:



                                            public static string Combine(params string parts)
                                        {
                                        if (parts == null || parts.Length == 0) return string.Empty;

                                        var urlBuilder = new StringBuilder();
                                        foreach (var part in parts)
                                        {
                                        var tempUrl = tryCreateRelativeOrAbsolute(part);
                                        urlBuilder.Append(tempUrl);
                                        }
                                        return VirtualPathUtility.RemoveTrailingSlash(urlBuilder.ToString());
                                        }

                                        private static string tryCreateRelativeOrAbsolute(string s)
                                        {
                                        System.Uri uri;
                                        System.Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri);
                                        string tempUrl = VirtualPathUtility.AppendTrailingSlash(uri.ToString());
                                        return tempUrl;
                                        }


                                        Full code with unit tests to demonstrate usage can be found at https://uricombine.codeplex.com/SourceControl/latest#UriCombine/Uri.cs



                                        I have unit tests to cover the three most common cases:



                                        Enter image description here






                                        share|improve this answer





















                                        • 1





                                          Looks pretty good to me. Although you could replace the I loop with a foreach loop for better clarity.

                                          – Chris Marisic
                                          May 1 '14 at 18:55











                                        • Thanks Chris. I have just changed my code to use Foreach.

                                          – Believe2014
                                          May 2 '14 at 4:03






                                        • 1





                                          +1 for all the extra effort. I need to maintain this question a bit for some of the higher voted answers, you have thrown down the gauntlet. ;)

                                          – Brian MacKay
                                          May 4 '14 at 11:42













                                        • Sorry, but not enough. Works in the few cases you show but far from being usable in al combinations. For instance, colons in the path will cause harm.

                                          – Gábor
                                          May 13 '18 at 20:43











                                        • Can you please give an example of what you mean? I will be happy to fix the issue and help the next users.

                                          – Believe2014
                                          May 14 '18 at 21:23














                                        8












                                        8








                                        8







                                        Combining multiple parts of a URL could be a little bit tricky. You can use the two-parameter constructor Uri(baseUri, relativeUri), or you can use the Uri.TryCreate() utility function.



                                        In either case, you might end up returning an incorrect result because these methods keep on truncating the relative parts off of the first parameter baseUri, i.e. from something like http://google.com/some/thing to http://google.com.



                                        To be able to combine multiple parts into a final URL, you can copy the two functions below:



                                            public static string Combine(params string parts)
                                        {
                                        if (parts == null || parts.Length == 0) return string.Empty;

                                        var urlBuilder = new StringBuilder();
                                        foreach (var part in parts)
                                        {
                                        var tempUrl = tryCreateRelativeOrAbsolute(part);
                                        urlBuilder.Append(tempUrl);
                                        }
                                        return VirtualPathUtility.RemoveTrailingSlash(urlBuilder.ToString());
                                        }

                                        private static string tryCreateRelativeOrAbsolute(string s)
                                        {
                                        System.Uri uri;
                                        System.Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri);
                                        string tempUrl = VirtualPathUtility.AppendTrailingSlash(uri.ToString());
                                        return tempUrl;
                                        }


                                        Full code with unit tests to demonstrate usage can be found at https://uricombine.codeplex.com/SourceControl/latest#UriCombine/Uri.cs



                                        I have unit tests to cover the three most common cases:



                                        Enter image description here






                                        share|improve this answer















                                        Combining multiple parts of a URL could be a little bit tricky. You can use the two-parameter constructor Uri(baseUri, relativeUri), or you can use the Uri.TryCreate() utility function.



                                        In either case, you might end up returning an incorrect result because these methods keep on truncating the relative parts off of the first parameter baseUri, i.e. from something like http://google.com/some/thing to http://google.com.



                                        To be able to combine multiple parts into a final URL, you can copy the two functions below:



                                            public static string Combine(params string parts)
                                        {
                                        if (parts == null || parts.Length == 0) return string.Empty;

                                        var urlBuilder = new StringBuilder();
                                        foreach (var part in parts)
                                        {
                                        var tempUrl = tryCreateRelativeOrAbsolute(part);
                                        urlBuilder.Append(tempUrl);
                                        }
                                        return VirtualPathUtility.RemoveTrailingSlash(urlBuilder.ToString());
                                        }

                                        private static string tryCreateRelativeOrAbsolute(string s)
                                        {
                                        System.Uri uri;
                                        System.Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri);
                                        string tempUrl = VirtualPathUtility.AppendTrailingSlash(uri.ToString());
                                        return tempUrl;
                                        }


                                        Full code with unit tests to demonstrate usage can be found at https://uricombine.codeplex.com/SourceControl/latest#UriCombine/Uri.cs



                                        I have unit tests to cover the three most common cases:



                                        Enter image description here







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Oct 18 '18 at 19:52









                                        Peter Mortensen

                                        13.8k1987113




                                        13.8k1987113










                                        answered Apr 30 '14 at 22:21









                                        Believe2014Believe2014

                                        2,86511833




                                        2,86511833








                                        • 1





                                          Looks pretty good to me. Although you could replace the I loop with a foreach loop for better clarity.

                                          – Chris Marisic
                                          May 1 '14 at 18:55











                                        • Thanks Chris. I have just changed my code to use Foreach.

                                          – Believe2014
                                          May 2 '14 at 4:03






                                        • 1





                                          +1 for all the extra effort. I need to maintain this question a bit for some of the higher voted answers, you have thrown down the gauntlet. ;)

                                          – Brian MacKay
                                          May 4 '14 at 11:42













                                        • Sorry, but not enough. Works in the few cases you show but far from being usable in al combinations. For instance, colons in the path will cause harm.

                                          – Gábor
                                          May 13 '18 at 20:43











                                        • Can you please give an example of what you mean? I will be happy to fix the issue and help the next users.

                                          – Believe2014
                                          May 14 '18 at 21:23














                                        • 1





                                          Looks pretty good to me. Although you could replace the I loop with a foreach loop for better clarity.

                                          – Chris Marisic
                                          May 1 '14 at 18:55











                                        • Thanks Chris. I have just changed my code to use Foreach.

                                          – Believe2014
                                          May 2 '14 at 4:03






                                        • 1





                                          +1 for all the extra effort. I need to maintain this question a bit for some of the higher voted answers, you have thrown down the gauntlet. ;)

                                          – Brian MacKay
                                          May 4 '14 at 11:42













                                        • Sorry, but not enough. Works in the few cases you show but far from being usable in al combinations. For instance, colons in the path will cause harm.

                                          – Gábor
                                          May 13 '18 at 20:43











                                        • Can you please give an example of what you mean? I will be happy to fix the issue and help the next users.

                                          – Believe2014
                                          May 14 '18 at 21:23








                                        1




                                        1





                                        Looks pretty good to me. Although you could replace the I loop with a foreach loop for better clarity.

                                        – Chris Marisic
                                        May 1 '14 at 18:55





                                        Looks pretty good to me. Although you could replace the I loop with a foreach loop for better clarity.

                                        – Chris Marisic
                                        May 1 '14 at 18:55













                                        Thanks Chris. I have just changed my code to use Foreach.

                                        – Believe2014
                                        May 2 '14 at 4:03





                                        Thanks Chris. I have just changed my code to use Foreach.

                                        – Believe2014
                                        May 2 '14 at 4:03




                                        1




                                        1





                                        +1 for all the extra effort. I need to maintain this question a bit for some of the higher voted answers, you have thrown down the gauntlet. ;)

                                        – Brian MacKay
                                        May 4 '14 at 11:42







                                        +1 for all the extra effort. I need to maintain this question a bit for some of the higher voted answers, you have thrown down the gauntlet. ;)

                                        – Brian MacKay
                                        May 4 '14 at 11:42















                                        Sorry, but not enough. Works in the few cases you show but far from being usable in al combinations. For instance, colons in the path will cause harm.

                                        – Gábor
                                        May 13 '18 at 20:43





                                        Sorry, but not enough. Works in the few cases you show but far from being usable in al combinations. For instance, colons in the path will cause harm.

                                        – Gábor
                                        May 13 '18 at 20:43













                                        Can you please give an example of what you mean? I will be happy to fix the issue and help the next users.

                                        – Believe2014
                                        May 14 '18 at 21:23





                                        Can you please give an example of what you mean? I will be happy to fix the issue and help the next users.

                                        – Believe2014
                                        May 14 '18 at 21:23











                                        7














                                        I found UriBuilder worked really well for this sort of thing:



                                        UriBuilder urlb = new UriBuilder("http", _serverAddress, _webPort, _filePath);
                                        Uri url = urlb.Uri;
                                        return url.AbsoluteUri;


                                        See UriBuilder Class - MSDN for more constructors and documentation.






                                        share|improve this answer






























                                          7














                                          I found UriBuilder worked really well for this sort of thing:



                                          UriBuilder urlb = new UriBuilder("http", _serverAddress, _webPort, _filePath);
                                          Uri url = urlb.Uri;
                                          return url.AbsoluteUri;


                                          See UriBuilder Class - MSDN for more constructors and documentation.






                                          share|improve this answer




























                                            7












                                            7








                                            7







                                            I found UriBuilder worked really well for this sort of thing:



                                            UriBuilder urlb = new UriBuilder("http", _serverAddress, _webPort, _filePath);
                                            Uri url = urlb.Uri;
                                            return url.AbsoluteUri;


                                            See UriBuilder Class - MSDN for more constructors and documentation.






                                            share|improve this answer















                                            I found UriBuilder worked really well for this sort of thing:



                                            UriBuilder urlb = new UriBuilder("http", _serverAddress, _webPort, _filePath);
                                            Uri url = urlb.Uri;
                                            return url.AbsoluteUri;


                                            See UriBuilder Class - MSDN for more constructors and documentation.







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Oct 18 '18 at 19:55









                                            Peter Mortensen

                                            13.8k1987113




                                            13.8k1987113










                                            answered May 22 '13 at 12:19









                                            javajavajavajavajavajavajavajavajavajava

                                            7302919




                                            7302919























                                                7














                                                An easy way to combine them and ensure it's always correct is:



                                                string.Format("{0}/{1}", Url1.Trim('/'), Url2);





                                                share|improve this answer


























                                                • +1, although this is very similiar to mdsharpe's answer, which I improved upon in my answer. This version works great unless Url2 starts with / or , or Url1 accidentally ends in , or either one is empty! :)

                                                  – Brian MacKay
                                                  May 12 '10 at 23:57
















                                                7














                                                An easy way to combine them and ensure it's always correct is:



                                                string.Format("{0}/{1}", Url1.Trim('/'), Url2);





                                                share|improve this answer


























                                                • +1, although this is very similiar to mdsharpe's answer, which I improved upon in my answer. This version works great unless Url2 starts with / or , or Url1 accidentally ends in , or either one is empty! :)

                                                  – Brian MacKay
                                                  May 12 '10 at 23:57














                                                7












                                                7








                                                7







                                                An easy way to combine them and ensure it's always correct is:



                                                string.Format("{0}/{1}", Url1.Trim('/'), Url2);





                                                share|improve this answer















                                                An easy way to combine them and ensure it's always correct is:



                                                string.Format("{0}/{1}", Url1.Trim('/'), Url2);






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Oct 18 '18 at 20:00









                                                Peter Mortensen

                                                13.8k1987113




                                                13.8k1987113










                                                answered May 12 '10 at 21:42









                                                AlexAlex

                                                8613




                                                8613













                                                • +1, although this is very similiar to mdsharpe's answer, which I improved upon in my answer. This version works great unless Url2 starts with / or , or Url1 accidentally ends in , or either one is empty! :)

                                                  – Brian MacKay
                                                  May 12 '10 at 23:57



















                                                • +1, although this is very similiar to mdsharpe's answer, which I improved upon in my answer. This version works great unless Url2 starts with / or , or Url1 accidentally ends in , or either one is empty! :)

                                                  – Brian MacKay
                                                  May 12 '10 at 23:57

















                                                +1, although this is very similiar to mdsharpe's answer, which I improved upon in my answer. This version works great unless Url2 starts with / or , or Url1 accidentally ends in , or either one is empty! :)

                                                – Brian MacKay
                                                May 12 '10 at 23:57





                                                +1, although this is very similiar to mdsharpe's answer, which I improved upon in my answer. This version works great unless Url2 starts with / or , or Url1 accidentally ends in , or either one is empty! :)

                                                – Brian MacKay
                                                May 12 '10 at 23:57











                                                4














                                                Here's Microsoft's (OfficeDev PnP) method UrlUtility.Combine:



                                                    const char PATH_DELIMITER = '/';

                                                /// <summary>
                                                /// Combines a path and a relative path.
                                                /// </summary>
                                                /// <param name="path"></param>
                                                /// <param name="relative"></param>
                                                /// <returns></returns>
                                                public static string Combine(string path, string relative)
                                                {
                                                if(relative == null)
                                                relative = String.Empty;

                                                if(path == null)
                                                path = String.Empty;

                                                if(relative.Length == 0 && path.Length == 0)
                                                return String.Empty;

                                                if(relative.Length == 0)
                                                return path;

                                                if(path.Length == 0)
                                                return relative;

                                                path = path.Replace('\', PATH_DELIMITER);
                                                relative = relative.Replace('\', PATH_DELIMITER);

                                                return path.TrimEnd(PATH_DELIMITER) + PATH_DELIMITER + relative.TrimStart(PATH_DELIMITER);
                                                }


                                                Source: GitHub






                                                share|improve this answer


























                                                • It looks like this might be for paths, rather than URLs.

                                                  – Brian MacKay
                                                  Nov 2 '15 at 18:12











                                                • @BrianMacKay Agreed that it looks like it, but it's from the UrlUtility class and used in the context of combining URLs

                                                  – user3638471
                                                  Nov 3 '15 at 19:55






                                                • 2





                                                  Edited to clarify what class it belongs to

                                                  – user3638471
                                                  Nov 3 '15 at 19:57











                                                • Take care when using this Class, the rest of the class contains SharePoint specific artifacts.

                                                  – Harry Berry
                                                  Sep 26 '17 at 12:55
















                                                4














                                                Here's Microsoft's (OfficeDev PnP) method UrlUtility.Combine:



                                                    const char PATH_DELIMITER = '/';

                                                /// <summary>
                                                /// Combines a path and a relative path.
                                                /// </summary>
                                                /// <param name="path"></param>
                                                /// <param name="relative"></param>
                                                /// <returns></returns>
                                                public static string Combine(string path, string relative)
                                                {
                                                if(relative == null)
                                                relative = String.Empty;

                                                if(path == null)
                                                path = String.Empty;

                                                if(relative.Length == 0 && path.Length == 0)
                                                return String.Empty;

                                                if(relative.Length == 0)
                                                return path;

                                                if(path.Length == 0)
                                                return relative;

                                                path = path.Replace('\', PATH_DELIMITER);
                                                relative = relative.Replace('\', PATH_DELIMITER);

                                                return path.TrimEnd(PATH_DELIMITER) + PATH_DELIMITER + relative.TrimStart(PATH_DELIMITER);
                                                }


                                                Source: GitHub






                                                share|improve this answer


























                                                • It looks like this might be for paths, rather than URLs.

                                                  – Brian MacKay
                                                  Nov 2 '15 at 18:12











                                                • @BrianMacKay Agreed that it looks like it, but it's from the UrlUtility class and used in the context of combining URLs

                                                  – user3638471
                                                  Nov 3 '15 at 19:55






                                                • 2





                                                  Edited to clarify what class it belongs to

                                                  – user3638471
                                                  Nov 3 '15 at 19:57











                                                • Take care when using this Class, the rest of the class contains SharePoint specific artifacts.

                                                  – Harry Berry
                                                  Sep 26 '17 at 12:55














                                                4












                                                4








                                                4







                                                Here's Microsoft's (OfficeDev PnP) method UrlUtility.Combine:



                                                    const char PATH_DELIMITER = '/';

                                                /// <summary>
                                                /// Combines a path and a relative path.
                                                /// </summary>
                                                /// <param name="path"></param>
                                                /// <param name="relative"></param>
                                                /// <returns></returns>
                                                public static string Combine(string path, string relative)
                                                {
                                                if(relative == null)
                                                relative = String.Empty;

                                                if(path == null)
                                                path = String.Empty;

                                                if(relative.Length == 0 && path.Length == 0)
                                                return String.Empty;

                                                if(relative.Length == 0)
                                                return path;

                                                if(path.Length == 0)
                                                return relative;

                                                path = path.Replace('\', PATH_DELIMITER);
                                                relative = relative.Replace('\', PATH_DELIMITER);

                                                return path.TrimEnd(PATH_DELIMITER) + PATH_DELIMITER + relative.TrimStart(PATH_DELIMITER);
                                                }


                                                Source: GitHub






                                                share|improve this answer















                                                Here's Microsoft's (OfficeDev PnP) method UrlUtility.Combine:



                                                    const char PATH_DELIMITER = '/';

                                                /// <summary>
                                                /// Combines a path and a relative path.
                                                /// </summary>
                                                /// <param name="path"></param>
                                                /// <param name="relative"></param>
                                                /// <returns></returns>
                                                public static string Combine(string path, string relative)
                                                {
                                                if(relative == null)
                                                relative = String.Empty;

                                                if(path == null)
                                                path = String.Empty;

                                                if(relative.Length == 0 && path.Length == 0)
                                                return String.Empty;

                                                if(relative.Length == 0)
                                                return path;

                                                if(path.Length == 0)
                                                return relative;

                                                path = path.Replace('\', PATH_DELIMITER);
                                                relative = relative.Replace('\', PATH_DELIMITER);

                                                return path.TrimEnd(PATH_DELIMITER) + PATH_DELIMITER + relative.TrimStart(PATH_DELIMITER);
                                                }


                                                Source: GitHub







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Jun 6 '17 at 21:25









                                                Chris Marisic

                                                22k18131235




                                                22k18131235










                                                answered Nov 1 '15 at 18:34







                                                user3638471




















                                                • It looks like this might be for paths, rather than URLs.

                                                  – Brian MacKay
                                                  Nov 2 '15 at 18:12











                                                • @BrianMacKay Agreed that it looks like it, but it's from the UrlUtility class and used in the context of combining URLs

                                                  – user3638471
                                                  Nov 3 '15 at 19:55






                                                • 2





                                                  Edited to clarify what class it belongs to

                                                  – user3638471
                                                  Nov 3 '15 at 19:57











                                                • Take care when using this Class, the rest of the class contains SharePoint specific artifacts.

                                                  – Harry Berry
                                                  Sep 26 '17 at 12:55



















                                                • It looks like this might be for paths, rather than URLs.

                                                  – Brian MacKay
                                                  Nov 2 '15 at 18:12











                                                • @BrianMacKay Agreed that it looks like it, but it's from the UrlUtility class and used in the context of combining URLs

                                                  – user3638471
                                                  Nov 3 '15 at 19:55






                                                • 2





                                                  Edited to clarify what class it belongs to

                                                  – user3638471
                                                  Nov 3 '15 at 19:57











                                                • Take care when using this Class, the rest of the class contains SharePoint specific artifacts.

                                                  – Harry Berry
                                                  Sep 26 '17 at 12:55

















                                                It looks like this might be for paths, rather than URLs.

                                                – Brian MacKay
                                                Nov 2 '15 at 18:12





                                                It looks like this might be for paths, rather than URLs.

                                                – Brian MacKay
                                                Nov 2 '15 at 18:12













                                                @BrianMacKay Agreed that it looks like it, but it's from the UrlUtility class and used in the context of combining URLs

                                                – user3638471
                                                Nov 3 '15 at 19:55





                                                @BrianMacKay Agreed that it looks like it, but it's from the UrlUtility class and used in the context of combining URLs

                                                – user3638471
                                                Nov 3 '15 at 19:55




                                                2




                                                2





                                                Edited to clarify what class it belongs to

                                                – user3638471
                                                Nov 3 '15 at 19:57





                                                Edited to clarify what class it belongs to

                                                – user3638471
                                                Nov 3 '15 at 19:57













                                                Take care when using this Class, the rest of the class contains SharePoint specific artifacts.

                                                – Harry Berry
                                                Sep 26 '17 at 12:55





                                                Take care when using this Class, the rest of the class contains SharePoint specific artifacts.

                                                – Harry Berry
                                                Sep 26 '17 at 12:55











                                                3














                                                My generic solution:



                                                public static string Combine(params string uriParts)
                                                {
                                                string uri = string.Empty;
                                                if (uriParts != null && uriParts.Any())
                                                {
                                                char trims = new char { '\', '/' };
                                                uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);

                                                for (int i = 1; i < uriParts.Length; i++)
                                                {
                                                uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
                                                }
                                                }

                                                return uri;
                                                }





                                                share|improve this answer
























                                                • This helper method is very flexible and works well in many different use cases. Thank you!

                                                  – Shiva
                                                  May 22 '17 at 5:11
















                                                3














                                                My generic solution:



                                                public static string Combine(params string uriParts)
                                                {
                                                string uri = string.Empty;
                                                if (uriParts != null && uriParts.Any())
                                                {
                                                char trims = new char { '\', '/' };
                                                uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);

                                                for (int i = 1; i < uriParts.Length; i++)
                                                {
                                                uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
                                                }
                                                }

                                                return uri;
                                                }





                                                share|improve this answer
























                                                • This helper method is very flexible and works well in many different use cases. Thank you!

                                                  – Shiva
                                                  May 22 '17 at 5:11














                                                3












                                                3








                                                3







                                                My generic solution:



                                                public static string Combine(params string uriParts)
                                                {
                                                string uri = string.Empty;
                                                if (uriParts != null && uriParts.Any())
                                                {
                                                char trims = new char { '\', '/' };
                                                uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);

                                                for (int i = 1; i < uriParts.Length; i++)
                                                {
                                                uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
                                                }
                                                }

                                                return uri;
                                                }





                                                share|improve this answer













                                                My generic solution:



                                                public static string Combine(params string uriParts)
                                                {
                                                string uri = string.Empty;
                                                if (uriParts != null && uriParts.Any())
                                                {
                                                char trims = new char { '\', '/' };
                                                uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);

                                                for (int i = 1; i < uriParts.Length; i++)
                                                {
                                                uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
                                                }
                                                }

                                                return uri;
                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered May 17 '15 at 7:52









                                                Alex TitarenkoAlex Titarenko

                                                44137




                                                44137













                                                • This helper method is very flexible and works well in many different use cases. Thank you!

                                                  – Shiva
                                                  May 22 '17 at 5:11



















                                                • This helper method is very flexible and works well in many different use cases. Thank you!

                                                  – Shiva
                                                  May 22 '17 at 5:11

















                                                This helper method is very flexible and works well in many different use cases. Thank you!

                                                – Shiva
                                                May 22 '17 at 5:11





                                                This helper method is very flexible and works well in many different use cases. Thank you!

                                                – Shiva
                                                May 22 '17 at 5:11











                                                3














                                                I created this function that will make your life easier:



                                                    /// <summary>
                                                /// The ultimate Path combiner of all time
                                                /// </summary>
                                                /// <param name="IsURL">
                                                /// true - if the paths are Internet URLs, false - if the paths are local URLs, this is very important as this will be used to decide which separator will be used.
                                                /// </param>
                                                /// <param name="IsRelative">Just adds the separator at the beginning</param>
                                                /// <param name="IsFixInternal">Fix the paths from within (by removing duplicate separators and correcting the separators)</param>
                                                /// <param name="parts">The paths to combine</param>
                                                /// <returns>the combined path</returns>
                                                public static string PathCombine(bool IsURL , bool IsRelative , bool IsFixInternal , params string parts)
                                                {
                                                if (parts == null || parts.Length == 0) return string.Empty;
                                                char separator = IsURL ? '/' : '\';

                                                if (parts.Length == 1 && IsFixInternal)
                                                {
                                                string validsingle;
                                                if (IsURL)
                                                {
                                                validsingle = parts[0].Replace('\' , '/');
                                                }
                                                else
                                                {
                                                validsingle = parts[0].Replace('/' , '\');
                                                }
                                                validsingle = validsingle.Trim(separator);
                                                return (IsRelative ? separator.ToString() : string.Empty) + validsingle;
                                                }

                                                string final = parts
                                                .Aggregate
                                                (
                                                (string first , string second) =>
                                                {
                                                string validfirst;
                                                string validsecond;
                                                if (IsURL)
                                                {
                                                validfirst = first.Replace('\' , '/');
                                                validsecond = second.Replace('\' , '/');
                                                }
                                                else
                                                {
                                                validfirst = first.Replace('/' , '\');
                                                validsecond = second.Replace('/' , '\');
                                                }
                                                var prefix = string.Empty;
                                                if (IsFixInternal)
                                                {
                                                if (IsURL)
                                                {
                                                if (validfirst.Contains("://"))
                                                {
                                                var tofix = validfirst.Substring(validfirst.IndexOf("://") + 3);
                                                prefix = validfirst.Replace(tofix , string.Empty).TrimStart(separator);

                                                var tofixlist = tofix.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

                                                validfirst = separator + string.Join(separator.ToString() , tofixlist);
                                                }
                                                else
                                                {
                                                var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                validfirst = string.Join(separator.ToString() , firstlist);
                                                }

                                                var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                validsecond = string.Join(separator.ToString() , secondlist);
                                                }
                                                else
                                                {
                                                var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

                                                validfirst = string.Join(separator.ToString() , firstlist);
                                                validsecond = string.Join(separator.ToString() , secondlist);
                                                }
                                                }
                                                return prefix + validfirst.Trim(separator) + separator + validsecond.Trim(separator);
                                                }
                                                );
                                                return (IsRelative ? separator.ToString() : string.Empty) + final;
                                                }


                                                It works for URLs as well as normal paths.



                                                Usage:



                                                    // Fixes internal paths
                                                Console.WriteLine(PathCombine(true , true , true , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                // Result: /folder 1/folder2/folder3/somefile.ext

                                                // Doesn't fix internal paths
                                                Console.WriteLine(PathCombine(true , true , false , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                //result : /folder 1//////////folder2////folder3/somefile.ext

                                                // Don't worry about URL prefixes when fixing internal paths
                                                Console.WriteLine(PathCombine(true , false , true , @"///https:///lul.com///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                // Result: https://lul.com/folder2/folder3/somefile.ext

                                                Console.WriteLine(PathCombine(false , true , true , @"../../../\....../../somepath" , @"anotherpath"));
                                                // Result: ..............somepathanotherpath





                                                share|improve this answer






























                                                  3














                                                  I created this function that will make your life easier:



                                                      /// <summary>
                                                  /// The ultimate Path combiner of all time
                                                  /// </summary>
                                                  /// <param name="IsURL">
                                                  /// true - if the paths are Internet URLs, false - if the paths are local URLs, this is very important as this will be used to decide which separator will be used.
                                                  /// </param>
                                                  /// <param name="IsRelative">Just adds the separator at the beginning</param>
                                                  /// <param name="IsFixInternal">Fix the paths from within (by removing duplicate separators and correcting the separators)</param>
                                                  /// <param name="parts">The paths to combine</param>
                                                  /// <returns>the combined path</returns>
                                                  public static string PathCombine(bool IsURL , bool IsRelative , bool IsFixInternal , params string parts)
                                                  {
                                                  if (parts == null || parts.Length == 0) return string.Empty;
                                                  char separator = IsURL ? '/' : '\';

                                                  if (parts.Length == 1 && IsFixInternal)
                                                  {
                                                  string validsingle;
                                                  if (IsURL)
                                                  {
                                                  validsingle = parts[0].Replace('\' , '/');
                                                  }
                                                  else
                                                  {
                                                  validsingle = parts[0].Replace('/' , '\');
                                                  }
                                                  validsingle = validsingle.Trim(separator);
                                                  return (IsRelative ? separator.ToString() : string.Empty) + validsingle;
                                                  }

                                                  string final = parts
                                                  .Aggregate
                                                  (
                                                  (string first , string second) =>
                                                  {
                                                  string validfirst;
                                                  string validsecond;
                                                  if (IsURL)
                                                  {
                                                  validfirst = first.Replace('\' , '/');
                                                  validsecond = second.Replace('\' , '/');
                                                  }
                                                  else
                                                  {
                                                  validfirst = first.Replace('/' , '\');
                                                  validsecond = second.Replace('/' , '\');
                                                  }
                                                  var prefix = string.Empty;
                                                  if (IsFixInternal)
                                                  {
                                                  if (IsURL)
                                                  {
                                                  if (validfirst.Contains("://"))
                                                  {
                                                  var tofix = validfirst.Substring(validfirst.IndexOf("://") + 3);
                                                  prefix = validfirst.Replace(tofix , string.Empty).TrimStart(separator);

                                                  var tofixlist = tofix.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

                                                  validfirst = separator + string.Join(separator.ToString() , tofixlist);
                                                  }
                                                  else
                                                  {
                                                  var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                  validfirst = string.Join(separator.ToString() , firstlist);
                                                  }

                                                  var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                  validsecond = string.Join(separator.ToString() , secondlist);
                                                  }
                                                  else
                                                  {
                                                  var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                  var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

                                                  validfirst = string.Join(separator.ToString() , firstlist);
                                                  validsecond = string.Join(separator.ToString() , secondlist);
                                                  }
                                                  }
                                                  return prefix + validfirst.Trim(separator) + separator + validsecond.Trim(separator);
                                                  }
                                                  );
                                                  return (IsRelative ? separator.ToString() : string.Empty) + final;
                                                  }


                                                  It works for URLs as well as normal paths.



                                                  Usage:



                                                      // Fixes internal paths
                                                  Console.WriteLine(PathCombine(true , true , true , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                  // Result: /folder 1/folder2/folder3/somefile.ext

                                                  // Doesn't fix internal paths
                                                  Console.WriteLine(PathCombine(true , true , false , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                  //result : /folder 1//////////folder2////folder3/somefile.ext

                                                  // Don't worry about URL prefixes when fixing internal paths
                                                  Console.WriteLine(PathCombine(true , false , true , @"///https:///lul.com///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                  // Result: https://lul.com/folder2/folder3/somefile.ext

                                                  Console.WriteLine(PathCombine(false , true , true , @"../../../\....../../somepath" , @"anotherpath"));
                                                  // Result: ..............somepathanotherpath





                                                  share|improve this answer




























                                                    3












                                                    3








                                                    3







                                                    I created this function that will make your life easier:



                                                        /// <summary>
                                                    /// The ultimate Path combiner of all time
                                                    /// </summary>
                                                    /// <param name="IsURL">
                                                    /// true - if the paths are Internet URLs, false - if the paths are local URLs, this is very important as this will be used to decide which separator will be used.
                                                    /// </param>
                                                    /// <param name="IsRelative">Just adds the separator at the beginning</param>
                                                    /// <param name="IsFixInternal">Fix the paths from within (by removing duplicate separators and correcting the separators)</param>
                                                    /// <param name="parts">The paths to combine</param>
                                                    /// <returns>the combined path</returns>
                                                    public static string PathCombine(bool IsURL , bool IsRelative , bool IsFixInternal , params string parts)
                                                    {
                                                    if (parts == null || parts.Length == 0) return string.Empty;
                                                    char separator = IsURL ? '/' : '\';

                                                    if (parts.Length == 1 && IsFixInternal)
                                                    {
                                                    string validsingle;
                                                    if (IsURL)
                                                    {
                                                    validsingle = parts[0].Replace('\' , '/');
                                                    }
                                                    else
                                                    {
                                                    validsingle = parts[0].Replace('/' , '\');
                                                    }
                                                    validsingle = validsingle.Trim(separator);
                                                    return (IsRelative ? separator.ToString() : string.Empty) + validsingle;
                                                    }

                                                    string final = parts
                                                    .Aggregate
                                                    (
                                                    (string first , string second) =>
                                                    {
                                                    string validfirst;
                                                    string validsecond;
                                                    if (IsURL)
                                                    {
                                                    validfirst = first.Replace('\' , '/');
                                                    validsecond = second.Replace('\' , '/');
                                                    }
                                                    else
                                                    {
                                                    validfirst = first.Replace('/' , '\');
                                                    validsecond = second.Replace('/' , '\');
                                                    }
                                                    var prefix = string.Empty;
                                                    if (IsFixInternal)
                                                    {
                                                    if (IsURL)
                                                    {
                                                    if (validfirst.Contains("://"))
                                                    {
                                                    var tofix = validfirst.Substring(validfirst.IndexOf("://") + 3);
                                                    prefix = validfirst.Replace(tofix , string.Empty).TrimStart(separator);

                                                    var tofixlist = tofix.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

                                                    validfirst = separator + string.Join(separator.ToString() , tofixlist);
                                                    }
                                                    else
                                                    {
                                                    var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                    validfirst = string.Join(separator.ToString() , firstlist);
                                                    }

                                                    var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                    validsecond = string.Join(separator.ToString() , secondlist);
                                                    }
                                                    else
                                                    {
                                                    var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                    var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

                                                    validfirst = string.Join(separator.ToString() , firstlist);
                                                    validsecond = string.Join(separator.ToString() , secondlist);
                                                    }
                                                    }
                                                    return prefix + validfirst.Trim(separator) + separator + validsecond.Trim(separator);
                                                    }
                                                    );
                                                    return (IsRelative ? separator.ToString() : string.Empty) + final;
                                                    }


                                                    It works for URLs as well as normal paths.



                                                    Usage:



                                                        // Fixes internal paths
                                                    Console.WriteLine(PathCombine(true , true , true , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                    // Result: /folder 1/folder2/folder3/somefile.ext

                                                    // Doesn't fix internal paths
                                                    Console.WriteLine(PathCombine(true , true , false , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                    //result : /folder 1//////////folder2////folder3/somefile.ext

                                                    // Don't worry about URL prefixes when fixing internal paths
                                                    Console.WriteLine(PathCombine(true , false , true , @"///https:///lul.com///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                    // Result: https://lul.com/folder2/folder3/somefile.ext

                                                    Console.WriteLine(PathCombine(false , true , true , @"../../../\....../../somepath" , @"anotherpath"));
                                                    // Result: ..............somepathanotherpath





                                                    share|improve this answer















                                                    I created this function that will make your life easier:



                                                        /// <summary>
                                                    /// The ultimate Path combiner of all time
                                                    /// </summary>
                                                    /// <param name="IsURL">
                                                    /// true - if the paths are Internet URLs, false - if the paths are local URLs, this is very important as this will be used to decide which separator will be used.
                                                    /// </param>
                                                    /// <param name="IsRelative">Just adds the separator at the beginning</param>
                                                    /// <param name="IsFixInternal">Fix the paths from within (by removing duplicate separators and correcting the separators)</param>
                                                    /// <param name="parts">The paths to combine</param>
                                                    /// <returns>the combined path</returns>
                                                    public static string PathCombine(bool IsURL , bool IsRelative , bool IsFixInternal , params string parts)
                                                    {
                                                    if (parts == null || parts.Length == 0) return string.Empty;
                                                    char separator = IsURL ? '/' : '\';

                                                    if (parts.Length == 1 && IsFixInternal)
                                                    {
                                                    string validsingle;
                                                    if (IsURL)
                                                    {
                                                    validsingle = parts[0].Replace('\' , '/');
                                                    }
                                                    else
                                                    {
                                                    validsingle = parts[0].Replace('/' , '\');
                                                    }
                                                    validsingle = validsingle.Trim(separator);
                                                    return (IsRelative ? separator.ToString() : string.Empty) + validsingle;
                                                    }

                                                    string final = parts
                                                    .Aggregate
                                                    (
                                                    (string first , string second) =>
                                                    {
                                                    string validfirst;
                                                    string validsecond;
                                                    if (IsURL)
                                                    {
                                                    validfirst = first.Replace('\' , '/');
                                                    validsecond = second.Replace('\' , '/');
                                                    }
                                                    else
                                                    {
                                                    validfirst = first.Replace('/' , '\');
                                                    validsecond = second.Replace('/' , '\');
                                                    }
                                                    var prefix = string.Empty;
                                                    if (IsFixInternal)
                                                    {
                                                    if (IsURL)
                                                    {
                                                    if (validfirst.Contains("://"))
                                                    {
                                                    var tofix = validfirst.Substring(validfirst.IndexOf("://") + 3);
                                                    prefix = validfirst.Replace(tofix , string.Empty).TrimStart(separator);

                                                    var tofixlist = tofix.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

                                                    validfirst = separator + string.Join(separator.ToString() , tofixlist);
                                                    }
                                                    else
                                                    {
                                                    var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                    validfirst = string.Join(separator.ToString() , firstlist);
                                                    }

                                                    var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                    validsecond = string.Join(separator.ToString() , secondlist);
                                                    }
                                                    else
                                                    {
                                                    var firstlist = validfirst.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);
                                                    var secondlist = validsecond.Split(new { separator } , StringSplitOptions.RemoveEmptyEntries);

                                                    validfirst = string.Join(separator.ToString() , firstlist);
                                                    validsecond = string.Join(separator.ToString() , secondlist);
                                                    }
                                                    }
                                                    return prefix + validfirst.Trim(separator) + separator + validsecond.Trim(separator);
                                                    }
                                                    );
                                                    return (IsRelative ? separator.ToString() : string.Empty) + final;
                                                    }


                                                    It works for URLs as well as normal paths.



                                                    Usage:



                                                        // Fixes internal paths
                                                    Console.WriteLine(PathCombine(true , true , true , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                    // Result: /folder 1/folder2/folder3/somefile.ext

                                                    // Doesn't fix internal paths
                                                    Console.WriteLine(PathCombine(true , true , false , @"//folder 1///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                    //result : /folder 1//////////folder2////folder3/somefile.ext

                                                    // Don't worry about URL prefixes when fixing internal paths
                                                    Console.WriteLine(PathCombine(true , false , true , @"///https:///lul.com///\/folder2///folder3\/" , @"/somefile.ext///"));
                                                    // Result: https://lul.com/folder2/folder3/somefile.ext

                                                    Console.WriteLine(PathCombine(false , true , true , @"../../../\....../../somepath" , @"anotherpath"));
                                                    // Result: ..............somepathanotherpath






                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Oct 18 '18 at 20:04









                                                    Peter Mortensen

                                                    13.8k1987113




                                                    13.8k1987113










                                                    answered Jul 21 '16 at 18:19









                                                    bigworld12bigworld12

                                                    583626




                                                    583626























                                                        3














                                                        I find the following useful and has the following features :




                                                        • Throws on null or white space

                                                        • Takes multiple params parameter for multiple Url segments

                                                        • throws on null or empty


                                                        Class



                                                        public static class UrlPath
                                                        {
                                                        private static string InternalCombine(string source, string dest)
                                                        {
                                                        if (string.IsNullOrWhiteSpace(source))
                                                        throw new ArgumentException("Cannot be null or white space", nameof(source));

                                                        if (string.IsNullOrWhiteSpace(dest))
                                                        throw new ArgumentException("Cannot be null or white space", nameof(dest));

                                                        return $"{source.TrimEnd('/', '\')}/{dest.TrimStart('/', '\')}";
                                                        }

                                                        public static string Combine(string source, params string args)
                                                        => args.Aggregate(source, InternalCombine);
                                                        }


                                                        Tests



                                                        UrlPath.Combine("test1", "test2");
                                                        UrlPath.Combine("test1//", "test2");
                                                        UrlPath.Combine("test1", "/test2");

                                                        // Result = test1/test2

                                                        UrlPath.Combine(@"test1///", @"//\\//test2", @"//\\//test3") ;

                                                        // Result = test1/test2/test3

                                                        UrlPath.Combine("/test1/", "/test2/", null);
                                                        UrlPath.Combine("", "/test2/");
                                                        UrlPath.Combine("/test1/", null);

                                                        // Throws an ArgumentException





                                                        share|improve this answer


























                                                        • @PeterMortensen thanks for the edit

                                                          – Michael Randall
                                                          Oct 18 '18 at 23:14
















                                                        3














                                                        I find the following useful and has the following features :




                                                        • Throws on null or white space

                                                        • Takes multiple params parameter for multiple Url segments

                                                        • throws on null or empty


                                                        Class



                                                        public static class UrlPath
                                                        {
                                                        private static string InternalCombine(string source, string dest)
                                                        {
                                                        if (string.IsNullOrWhiteSpace(source))
                                                        throw new ArgumentException("Cannot be null or white space", nameof(source));

                                                        if (string.IsNullOrWhiteSpace(dest))
                                                        throw new ArgumentException("Cannot be null or white space", nameof(dest));

                                                        return $"{source.TrimEnd('/', '\')}/{dest.TrimStart('/', '\')}";
                                                        }

                                                        public static string Combine(string source, params string args)
                                                        => args.Aggregate(source, InternalCombine);
                                                        }


                                                        Tests



                                                        UrlPath.Combine("test1", "test2");
                                                        UrlPath.Combine("test1//", "test2");
                                                        UrlPath.Combine("test1", "/test2");

                                                        // Result = test1/test2

                                                        UrlPath.Combine(@"test1///", @"//\\//test2", @"//\\//test3") ;

                                                        // Result = test1/test2/test3

                                                        UrlPath.Combine("/test1/", "/test2/", null);
                                                        UrlPath.Combine("", "/test2/");
                                                        UrlPath.Combine("/test1/", null);

                                                        // Throws an ArgumentException





                                                        share|improve this answer


























                                                        • @PeterMortensen thanks for the edit

                                                          – Michael Randall
                                                          Oct 18 '18 at 23:14














                                                        3












                                                        3








                                                        3







                                                        I find the following useful and has the following features :




                                                        • Throws on null or white space

                                                        • Takes multiple params parameter for multiple Url segments

                                                        • throws on null or empty


                                                        Class



                                                        public static class UrlPath
                                                        {
                                                        private static string InternalCombine(string source, string dest)
                                                        {
                                                        if (string.IsNullOrWhiteSpace(source))
                                                        throw new ArgumentException("Cannot be null or white space", nameof(source));

                                                        if (string.IsNullOrWhiteSpace(dest))
                                                        throw new ArgumentException("Cannot be null or white space", nameof(dest));

                                                        return $"{source.TrimEnd('/', '\')}/{dest.TrimStart('/', '\')}";
                                                        }

                                                        public static string Combine(string source, params string args)
                                                        => args.Aggregate(source, InternalCombine);
                                                        }


                                                        Tests



                                                        UrlPath.Combine("test1", "test2");
                                                        UrlPath.Combine("test1//", "test2");
                                                        UrlPath.Combine("test1", "/test2");

                                                        // Result = test1/test2

                                                        UrlPath.Combine(@"test1///", @"//\\//test2", @"//\\//test3") ;

                                                        // Result = test1/test2/test3

                                                        UrlPath.Combine("/test1/", "/test2/", null);
                                                        UrlPath.Combine("", "/test2/");
                                                        UrlPath.Combine("/test1/", null);

                                                        // Throws an ArgumentException





                                                        share|improve this answer















                                                        I find the following useful and has the following features :




                                                        • Throws on null or white space

                                                        • Takes multiple params parameter for multiple Url segments

                                                        • throws on null or empty


                                                        Class



                                                        public static class UrlPath
                                                        {
                                                        private static string InternalCombine(string source, string dest)
                                                        {
                                                        if (string.IsNullOrWhiteSpace(source))
                                                        throw new ArgumentException("Cannot be null or white space", nameof(source));

                                                        if (string.IsNullOrWhiteSpace(dest))
                                                        throw new ArgumentException("Cannot be null or white space", nameof(dest));

                                                        return $"{source.TrimEnd('/', '\')}/{dest.TrimStart('/', '\')}";
                                                        }

                                                        public static string Combine(string source, params string args)
                                                        => args.Aggregate(source, InternalCombine);
                                                        }


                                                        Tests



                                                        UrlPath.Combine("test1", "test2");
                                                        UrlPath.Combine("test1//", "test2");
                                                        UrlPath.Combine("test1", "/test2");

                                                        // Result = test1/test2

                                                        UrlPath.Combine(@"test1///", @"//\\//test2", @"//\\//test3") ;

                                                        // Result = test1/test2/test3

                                                        UrlPath.Combine("/test1/", "/test2/", null);
                                                        UrlPath.Combine("", "/test2/");
                                                        UrlPath.Combine("/test1/", null);

                                                        // Throws an ArgumentException






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Oct 27 '18 at 1:18

























                                                        answered Feb 28 '17 at 2:11









                                                        Michael RandallMichael Randall

                                                        35.3k83869




                                                        35.3k83869













                                                        • @PeterMortensen thanks for the edit

                                                          – Michael Randall
                                                          Oct 18 '18 at 23:14



















                                                        • @PeterMortensen thanks for the edit

                                                          – Michael Randall
                                                          Oct 18 '18 at 23:14

















                                                        @PeterMortensen thanks for the edit

                                                        – Michael Randall
                                                        Oct 18 '18 at 23:14





                                                        @PeterMortensen thanks for the edit

                                                        – Michael Randall
                                                        Oct 18 '18 at 23:14











                                                        2














                                                        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();
                                                        });





                                                        share|improve this answer






























                                                          2














                                                          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();
                                                          });





                                                          share|improve this answer




























                                                            2












                                                            2








                                                            2







                                                            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();
                                                            });





                                                            share|improve this answer















                                                            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();
                                                            });






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Oct 18 '18 at 19:49









                                                            Peter Mortensen

                                                            13.8k1987113




                                                            13.8k1987113










                                                            answered Apr 5 '16 at 5:04









                                                            baHIbaHI

                                                            434511




                                                            434511























                                                                1














                                                                Use:



                                                                    private Uri UriCombine(string path1, string path2, string path3 = "", string path4 = "")
                                                                {
                                                                string path = System.IO.Path.Combine(path1, path2.TrimStart('\', '/'), path3.TrimStart('\', '/'), path4.TrimStart('\', '/'));
                                                                string url = path.Replace('\','/');
                                                                return new Uri(url);
                                                                }


                                                                It has the benefit of behaving exactly like Path.Combine.






                                                                share|improve this answer


























                                                                • see stackoverflow.com/a/4662962/1037948

                                                                  – drzaus
                                                                  Sep 10 '14 at 19:52


















                                                                1














                                                                Use:



                                                                    private Uri UriCombine(string path1, string path2, string path3 = "", string path4 = "")
                                                                {
                                                                string path = System.IO.Path.Combine(path1, path2.TrimStart('\', '/'), path3.TrimStart('\', '/'), path4.TrimStart('\', '/'));
                                                                string url = path.Replace('\','/');
                                                                return new Uri(url);
                                                                }


                                                                It has the benefit of behaving exactly like Path.Combine.






                                                                share|improve this answer


























                                                                • see stackoverflow.com/a/4662962/1037948

                                                                  – drzaus
                                                                  Sep 10 '14 at 19:52
















                                                                1












                                                                1








                                                                1







                                                                Use:



                                                                    private Uri UriCombine(string path1, string path2, string path3 = "", string path4 = "")
                                                                {
                                                                string path = System.IO.Path.Combine(path1, path2.TrimStart('\', '/'), path3.TrimStart('\', '/'), path4.TrimStart('\', '/'));
                                                                string url = path.Replace('\','/');
                                                                return new Uri(url);
                                                                }


                                                                It has the benefit of behaving exactly like Path.Combine.






                                                                share|improve this answer















                                                                Use:



                                                                    private Uri UriCombine(string path1, string path2, string path3 = "", string path4 = "")
                                                                {
                                                                string path = System.IO.Path.Combine(path1, path2.TrimStart('\', '/'), path3.TrimStart('\', '/'), path4.TrimStart('\', '/'));
                                                                string url = path.Replace('\','/');
                                                                return new Uri(url);
                                                                }


                                                                It has the benefit of behaving exactly like Path.Combine.







                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Oct 18 '18 at 19:53









                                                                Peter Mortensen

                                                                13.8k1987113




                                                                13.8k1987113










                                                                answered Feb 18 '14 at 15:31









                                                                TruthOf42TruthOf42

                                                                87931032




                                                                87931032













                                                                • see stackoverflow.com/a/4662962/1037948

                                                                  – drzaus
                                                                  Sep 10 '14 at 19:52





















                                                                • see stackoverflow.com/a/4662962/1037948

                                                                  – drzaus
                                                                  Sep 10 '14 at 19:52



















                                                                see stackoverflow.com/a/4662962/1037948

                                                                – drzaus
                                                                Sep 10 '14 at 19:52







                                                                see stackoverflow.com/a/4662962/1037948

                                                                – drzaus
                                                                Sep 10 '14 at 19:52













                                                                1














                                                                Here is my approach and I will use it for myself too:



                                                                public static string UrlCombine(string part1, string part2)
                                                                {
                                                                string newPart1 = string.Empty;
                                                                string newPart2 = string.Empty;
                                                                string seperator = "/";

                                                                // If either part1 or part 2 is empty,
                                                                // we don't need to combine with seperator
                                                                if (string.IsNullOrEmpty(part1) || string.IsNullOrEmpty(part2))
                                                                {
                                                                seperator = string.Empty;
                                                                }

                                                                // If part1 is not empty,
                                                                // remove '/' at last
                                                                if (!string.IsNullOrEmpty(part1))
                                                                {
                                                                newPart1 = part1.TrimEnd('/');
                                                                }

                                                                // If part2 is not empty,
                                                                // remove '/' at first
                                                                if (!string.IsNullOrEmpty(part2))
                                                                {
                                                                newPart2 = part2.TrimStart('/');
                                                                }

                                                                // Now finally combine
                                                                return string.Format("{0}{1}{2}", newPart1, seperator, newPart2);
                                                                }





                                                                share|improve this answer


























                                                                • This is acceptable only for your case. There are cases which could broke your code. Also, you didn't do proper encoding of the parts of the path. This could be a huge vulnerability when it comes to cross site scripting attack.

                                                                  – Believe2014
                                                                  May 1 '14 at 15:40











                                                                • I agree to your points. The code is supposed to do just simple combining of two url parts.

                                                                  – Amit Bhagat
                                                                  May 2 '14 at 3:14
















                                                                1














                                                                Here is my approach and I will use it for myself too:



                                                                public static string UrlCombine(string part1, string part2)
                                                                {
                                                                string newPart1 = string.Empty;
                                                                string newPart2 = string.Empty;
                                                                string seperator = "/";

                                                                // If either part1 or part 2 is empty,
                                                                // we don't need to combine with seperator
                                                                if (string.IsNullOrEmpty(part1) || string.IsNullOrEmpty(part2))
                                                                {
                                                                seperator = string.Empty;
                                                                }

                                                                // If part1 is not empty,
                                                                // remove '/' at last
                                                                if (!string.IsNullOrEmpty(part1))
                                                                {
                                                                newPart1 = part1.TrimEnd('/');
                                                                }

                                                                // If part2 is not empty,
                                                                // remove '/' at first
                                                                if (!string.IsNullOrEmpty(part2))
                                                                {
                                                                newPart2 = part2.TrimStart('/');
                                                                }

                                                                // Now finally combine
                                                                return string.Format("{0}{1}{2}", newPart1, seperator, newPart2);
                                                                }





                                                                share|improve this answer


























                                                                • This is acceptable only for your case. There are cases which could broke your code. Also, you didn't do proper encoding of the parts of the path. This could be a huge vulnerability when it comes to cross site scripting attack.

                                                                  – Believe2014
                                                                  May 1 '14 at 15:40











                                                                • I agree to your points. The code is supposed to do just simple combining of two url parts.

                                                                  – Amit Bhagat
                                                                  May 2 '14 at 3:14














                                                                1












                                                                1








                                                                1







                                                                Here is my approach and I will use it for myself too:



                                                                public static string UrlCombine(string part1, string part2)
                                                                {
                                                                string newPart1 = string.Empty;
                                                                string newPart2 = string.Empty;
                                                                string seperator = "/";

                                                                // If either part1 or part 2 is empty,
                                                                // we don't need to combine with seperator
                                                                if (string.IsNullOrEmpty(part1) || string.IsNullOrEmpty(part2))
                                                                {
                                                                seperator = string.Empty;
                                                                }

                                                                // If part1 is not empty,
                                                                // remove '/' at last
                                                                if (!string.IsNullOrEmpty(part1))
                                                                {
                                                                newPart1 = part1.TrimEnd('/');
                                                                }

                                                                // If part2 is not empty,
                                                                // remove '/' at first
                                                                if (!string.IsNullOrEmpty(part2))
                                                                {
                                                                newPart2 = part2.TrimStart('/');
                                                                }

                                                                // Now finally combine
                                                                return string.Format("{0}{1}{2}", newPart1, seperator, newPart2);
                                                                }





                                                                share|improve this answer















                                                                Here is my approach and I will use it for myself too:



                                                                public static string UrlCombine(string part1, string part2)
                                                                {
                                                                string newPart1 = string.Empty;
                                                                string newPart2 = string.Empty;
                                                                string seperator = "/";

                                                                // If either part1 or part 2 is empty,
                                                                // we don't need to combine with seperator
                                                                if (string.IsNullOrEmpty(part1) || string.IsNullOrEmpty(part2))
                                                                {
                                                                seperator = string.Empty;
                                                                }

                                                                // If part1 is not empty,
                                                                // remove '/' at last
                                                                if (!string.IsNullOrEmpty(part1))
                                                                {
                                                                newPart1 = part1.TrimEnd('/');
                                                                }

                                                                // If part2 is not empty,
                                                                // remove '/' at first
                                                                if (!string.IsNullOrEmpty(part2))
                                                                {
                                                                newPart2 = part2.TrimStart('/');
                                                                }

                                                                // Now finally combine
                                                                return string.Format("{0}{1}{2}", newPart1, seperator, newPart2);
                                                                }






                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Oct 18 '18 at 19:54









                                                                Peter Mortensen

                                                                13.8k1987113




                                                                13.8k1987113










                                                                answered Aug 3 '13 at 3:39









                                                                Amit BhagatAmit Bhagat

                                                                2,73021620




                                                                2,73021620













                                                                • This is acceptable only for your case. There are cases which could broke your code. Also, you didn't do proper encoding of the parts of the path. This could be a huge vulnerability when it comes to cross site scripting attack.

                                                                  – Believe2014
                                                                  May 1 '14 at 15:40











                                                                • I agree to your points. The code is supposed to do just simple combining of two url parts.

                                                                  – Amit Bhagat
                                                                  May 2 '14 at 3:14



















                                                                • This is acceptable only for your case. There are cases which could broke your code. Also, you didn't do proper encoding of the parts of the path. This could be a huge vulnerability when it comes to cross site scripting attack.

                                                                  – Believe2014
                                                                  May 1 '14 at 15:40











                                                                • I agree to your points. The code is supposed to do just simple combining of two url parts.

                                                                  – Amit Bhagat
                                                                  May 2 '14 at 3:14

















                                                                This is acceptable only for your case. There are cases which could broke your code. Also, you didn't do proper encoding of the parts of the path. This could be a huge vulnerability when it comes to cross site scripting attack.

                                                                – Believe2014
                                                                May 1 '14 at 15:40





                                                                This is acceptable only for your case. There are cases which could broke your code. Also, you didn't do proper encoding of the parts of the path. This could be a huge vulnerability when it comes to cross site scripting attack.

                                                                – Believe2014
                                                                May 1 '14 at 15:40













                                                                I agree to your points. The code is supposed to do just simple combining of two url parts.

                                                                – Amit Bhagat
                                                                May 2 '14 at 3:14





                                                                I agree to your points. The code is supposed to do just simple combining of two url parts.

                                                                – Amit Bhagat
                                                                May 2 '14 at 3:14











                                                                1














                                                                Use this:



                                                                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);
                                                                }
                                                                }





                                                                share|improve this answer


























                                                                • Nice touch with 'WebPath'. :) The code might be unecessarily dense though - it's hard for me to glance at this and say, yes, that's perfect. It makes me want to see unit tests. Maybe that's just me!

                                                                  – Brian MacKay
                                                                  Dec 10 '12 at 21:42








                                                                • 1





                                                                  x.StartsWith("/") && !x.StartsWith("http") - why the http check? what do you gain?

                                                                  – penguat
                                                                  Dec 13 '12 at 10:03











                                                                • You don't want to try to strip off the slash if it starts with http.

                                                                  – Martin Murphy
                                                                  Apr 16 '13 at 16:12











                                                                • @BrianMacKay, I'm not sure a two liner warrants a unit test but if you like feel free to provide one. It's not like I'm accepting patches or anything, but feel free to edit the suggestion.

                                                                  – Martin Murphy
                                                                  Apr 16 '13 at 16:23
















                                                                1














                                                                Use this:



                                                                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);
                                                                }
                                                                }





                                                                share|improve this answer


























                                                                • Nice touch with 'WebPath'. :) The code might be unecessarily dense though - it's hard for me to glance at this and say, yes, that's perfect. It makes me want to see unit tests. Maybe that's just me!

                                                                  – Brian MacKay
                                                                  Dec 10 '12 at 21:42








                                                                • 1





                                                                  x.StartsWith("/") && !x.StartsWith("http") - why the http check? what do you gain?

                                                                  – penguat
                                                                  Dec 13 '12 at 10:03











                                                                • You don't want to try to strip off the slash if it starts with http.

                                                                  – Martin Murphy
                                                                  Apr 16 '13 at 16:12











                                                                • @BrianMacKay, I'm not sure a two liner warrants a unit test but if you like feel free to provide one. It's not like I'm accepting patches or anything, but feel free to edit the suggestion.

                                                                  – Martin Murphy
                                                                  Apr 16 '13 at 16:23














                                                                1












                                                                1








                                                                1







                                                                Use this:



                                                                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);
                                                                }
                                                                }





                                                                share|improve this answer















                                                                Use this:



                                                                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);
                                                                }
                                                                }






                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Oct 18 '18 at 19:57









                                                                Peter Mortensen

                                                                13.8k1987113




                                                                13.8k1987113










                                                                answered Dec 10 '12 at 15:31









                                                                Martin MurphyMartin Murphy

                                                                1,52721423




                                                                1,52721423













                                                                • Nice touch with 'WebPath'. :) The code might be unecessarily dense though - it's hard for me to glance at this and say, yes, that's perfect. It makes me want to see unit tests. Maybe that's just me!

                                                                  – Brian MacKay
                                                                  Dec 10 '12 at 21:42








                                                                • 1





                                                                  x.StartsWith("/") && !x.StartsWith("http") - why the http check? what do you gain?

                                                                  – penguat
                                                                  Dec 13 '12 at 10:03











                                                                • You don't want to try to strip off the slash if it starts with http.

                                                                  – Martin Murphy
                                                                  Apr 16 '13 at 16:12











                                                                • @BrianMacKay, I'm not sure a two liner warrants a unit test but if you like feel free to provide one. It's not like I'm accepting patches or anything, but feel free to edit the suggestion.

                                                                  – Martin Murphy
                                                                  Apr 16 '13 at 16:23



















                                                                • Nice touch with 'WebPath'. :) The code might be unecessarily dense though - it's hard for me to glance at this and say, yes, that's perfect. It makes me want to see unit tests. Maybe that's just me!

                                                                  – Brian MacKay
                                                                  Dec 10 '12 at 21:42








                                                                • 1





                                                                  x.StartsWith("/") && !x.StartsWith("http") - why the http check? what do you gain?

                                                                  – penguat
                                                                  Dec 13 '12 at 10:03











                                                                • You don't want to try to strip off the slash if it starts with http.

                                                                  – Martin Murphy
                                                                  Apr 16 '13 at 16:12











                                                                • @BrianMacKay, I'm not sure a two liner warrants a unit test but if you like feel free to provide one. It's not like I'm accepting patches or anything, but feel free to edit the suggestion.

                                                                  – Martin Murphy
                                                                  Apr 16 '13 at 16:23

















                                                                Nice touch with 'WebPath'. :) The code might be unecessarily dense though - it's hard for me to glance at this and say, yes, that's perfect. It makes me want to see unit tests. Maybe that's just me!

                                                                – Brian MacKay
                                                                Dec 10 '12 at 21:42







                                                                Nice touch with 'WebPath'. :) The code might be unecessarily dense though - it's hard for me to glance at this and say, yes, that's perfect. It makes me want to see unit tests. Maybe that's just me!

                                                                – Brian MacKay
                                                                Dec 10 '12 at 21:42






                                                                1




                                                                1





                                                                x.StartsWith("/") && !x.StartsWith("http") - why the http check? what do you gain?

                                                                – penguat
                                                                Dec 13 '12 at 10:03





                                                                x.StartsWith("/") && !x.StartsWith("http") - why the http check? what do you gain?

                                                                – penguat
                                                                Dec 13 '12 at 10:03













                                                                You don't want to try to strip off the slash if it starts with http.

                                                                – Martin Murphy
                                                                Apr 16 '13 at 16:12





                                                                You don't want to try to strip off the slash if it starts with http.

                                                                – Martin Murphy
                                                                Apr 16 '13 at 16:12













                                                                @BrianMacKay, I'm not sure a two liner warrants a unit test but if you like feel free to provide one. It's not like I'm accepting patches or anything, but feel free to edit the suggestion.

                                                                – Martin Murphy
                                                                Apr 16 '13 at 16:23





                                                                @BrianMacKay, I'm not sure a two liner warrants a unit test but if you like feel free to provide one. It's not like I'm accepting patches or anything, but feel free to edit the suggestion.

                                                                – Martin Murphy
                                                                Apr 16 '13 at 16:23











                                                                1














                                                                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);





                                                                share|improve this answer






























                                                                  1














                                                                  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);





                                                                  share|improve this answer




























                                                                    1












                                                                    1








                                                                    1







                                                                    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);





                                                                    share|improve this answer















                                                                    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);






                                                                    share|improve this answer














                                                                    share|improve this answer



                                                                    share|improve this answer








                                                                    edited Oct 18 '18 at 20:10









                                                                    Peter Mortensen

                                                                    13.8k1987113




                                                                    13.8k1987113










                                                                    answered Sep 30 '18 at 10:43









                                                                    skippyskippy

                                                                    314




                                                                    314























                                                                        1














                                                                        Why not just use the following.



                                                                        System.IO.Path.Combine(rootUrl, subPath).Replace(@"", "/")





                                                                        share|improve this answer


























                                                                        • I was looking for the PowerShell version of this which would be: [System.IO.Path]::Combine("http://MyUrl.com/","/Images/Image.jpg")however this fails with a result of: /Images/Image.jpg. Remove the / from the second subPath and it works: [System.IO.Path]::Combine("http://MyUrl.com/","Images/Image.jpg")

                                                                          – Underverse
                                                                          Feb 6 '18 at 0:14











                                                                        • Nice idea, but it fails, when one of the parameter is null.

                                                                          – pholpar
                                                                          Mar 22 '18 at 14:19
















                                                                        1














                                                                        Why not just use the following.



                                                                        System.IO.Path.Combine(rootUrl, subPath).Replace(@"", "/")





                                                                        share|improve this answer


























                                                                        • I was looking for the PowerShell version of this which would be: [System.IO.Path]::Combine("http://MyUrl.com/","/Images/Image.jpg")however this fails with a result of: /Images/Image.jpg. Remove the / from the second subPath and it works: [System.IO.Path]::Combine("http://MyUrl.com/","Images/Image.jpg")

                                                                          – Underverse
                                                                          Feb 6 '18 at 0:14











                                                                        • Nice idea, but it fails, when one of the parameter is null.

                                                                          – pholpar
                                                                          Mar 22 '18 at 14:19














                                                                        1












                                                                        1








                                                                        1







                                                                        Why not just use the following.



                                                                        System.IO.Path.Combine(rootUrl, subPath).Replace(@"", "/")





                                                                        share|improve this answer















                                                                        Why not just use the following.



                                                                        System.IO.Path.Combine(rootUrl, subPath).Replace(@"", "/")






                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Oct 22 '18 at 8:42

























                                                                        answered Nov 17 '17 at 13:11









                                                                        AndreasAndreas

                                                                        2,29412645




                                                                        2,29412645













                                                                        • I was looking for the PowerShell version of this which would be: [System.IO.Path]::Combine("http://MyUrl.com/","/Images/Image.jpg")however this fails with a result of: /Images/Image.jpg. Remove the / from the second subPath and it works: [System.IO.Path]::Combine("http://MyUrl.com/","Images/Image.jpg")

                                                                          – Underverse
                                                                          Feb 6 '18 at 0:14











                                                                        • Nice idea, but it fails, when one of the parameter is null.

                                                                          – pholpar
                                                                          Mar 22 '18 at 14:19



















                                                                        • I was looking for the PowerShell version of this which would be: [System.IO.Path]::Combine("http://MyUrl.com/","/Images/Image.jpg")however this fails with a result of: /Images/Image.jpg. Remove the / from the second subPath and it works: [System.IO.Path]::Combine("http://MyUrl.com/","Images/Image.jpg")

                                                                          – Underverse
                                                                          Feb 6 '18 at 0:14











                                                                        • Nice idea, but it fails, when one of the parameter is null.

                                                                          – pholpar
                                                                          Mar 22 '18 at 14:19

















                                                                        I was looking for the PowerShell version of this which would be: [System.IO.Path]::Combine("http://MyUrl.com/","/Images/Image.jpg")however this fails with a result of: /Images/Image.jpg. Remove the / from the second subPath and it works: [System.IO.Path]::Combine("http://MyUrl.com/","Images/Image.jpg")

                                                                        – Underverse
                                                                        Feb 6 '18 at 0:14





                                                                        I was looking for the PowerShell version of this which would be: [System.IO.Path]::Combine("http://MyUrl.com/","/Images/Image.jpg")however this fails with a result of: /Images/Image.jpg. Remove the / from the second subPath and it works: [System.IO.Path]::Combine("http://MyUrl.com/","Images/Image.jpg")

                                                                        – Underverse
                                                                        Feb 6 '18 at 0:14













                                                                        Nice idea, but it fails, when one of the parameter is null.

                                                                        – pholpar
                                                                        Mar 22 '18 at 14:19





                                                                        Nice idea, but it fails, when one of the parameter is null.

                                                                        – pholpar
                                                                        Mar 22 '18 at 14:19











                                                                        0














                                                                        I used this code to solve the problem:



                                                                        string brokenBaseUrl = Context.Url.TrimEnd('/').Split('/');
                                                                        string brokenRootFolderPath = RootFolderPath.Split('/');

                                                                        for (int x = 0; x < brokenRootFolderPath.Length; x++)
                                                                        {
                                                                        //if url doesn't already contain member, append it to the end of the string with / in front
                                                                        if (!brokenBaseUrl.Contains(brokenRootFolderPath[x]))
                                                                        {
                                                                        if (x == 0)
                                                                        {
                                                                        RootLocationUrl = Context.Url.TrimEnd('/');
                                                                        }
                                                                        else
                                                                        {
                                                                        RootLocationUrl += String.Format("/{0}", brokenRootFolderPath[x]);
                                                                        }
                                                                        }
                                                                        }





                                                                        share|improve this answer






























                                                                          0














                                                                          I used this code to solve the problem:



                                                                          string brokenBaseUrl = Context.Url.TrimEnd('/').Split('/');
                                                                          string brokenRootFolderPath = RootFolderPath.Split('/');

                                                                          for (int x = 0; x < brokenRootFolderPath.Length; x++)
                                                                          {
                                                                          //if url doesn't already contain member, append it to the end of the string with / in front
                                                                          if (!brokenBaseUrl.Contains(brokenRootFolderPath[x]))
                                                                          {
                                                                          if (x == 0)
                                                                          {
                                                                          RootLocationUrl = Context.Url.TrimEnd('/');
                                                                          }
                                                                          else
                                                                          {
                                                                          RootLocationUrl += String.Format("/{0}", brokenRootFolderPath[x]);
                                                                          }
                                                                          }
                                                                          }





                                                                          share|improve this answer




























                                                                            0












                                                                            0








                                                                            0







                                                                            I used this code to solve the problem:



                                                                            string brokenBaseUrl = Context.Url.TrimEnd('/').Split('/');
                                                                            string brokenRootFolderPath = RootFolderPath.Split('/');

                                                                            for (int x = 0; x < brokenRootFolderPath.Length; x++)
                                                                            {
                                                                            //if url doesn't already contain member, append it to the end of the string with / in front
                                                                            if (!brokenBaseUrl.Contains(brokenRootFolderPath[x]))
                                                                            {
                                                                            if (x == 0)
                                                                            {
                                                                            RootLocationUrl = Context.Url.TrimEnd('/');
                                                                            }
                                                                            else
                                                                            {
                                                                            RootLocationUrl += String.Format("/{0}", brokenRootFolderPath[x]);
                                                                            }
                                                                            }
                                                                            }





                                                                            share|improve this answer















                                                                            I used this code to solve the problem:



                                                                            string brokenBaseUrl = Context.Url.TrimEnd('/').Split('/');
                                                                            string brokenRootFolderPath = RootFolderPath.Split('/');

                                                                            for (int x = 0; x < brokenRootFolderPath.Length; x++)
                                                                            {
                                                                            //if url doesn't already contain member, append it to the end of the string with / in front
                                                                            if (!brokenBaseUrl.Contains(brokenRootFolderPath[x]))
                                                                            {
                                                                            if (x == 0)
                                                                            {
                                                                            RootLocationUrl = Context.Url.TrimEnd('/');
                                                                            }
                                                                            else
                                                                            {
                                                                            RootLocationUrl += String.Format("/{0}", brokenRootFolderPath[x]);
                                                                            }
                                                                            }
                                                                            }






                                                                            share|improve this answer














                                                                            share|improve this answer



                                                                            share|improve this answer








                                                                            edited Mar 17 '16 at 15:50









                                                                            gunr2171

                                                                            7,608104767




                                                                            7,608104767










                                                                            answered Dec 3 '15 at 23:17









                                                                            Joshua SmithJoshua Smith

                                                                            11110




                                                                            11110























                                                                                0














                                                                                A simple one liner:



                                                                                public static string Combine(this string uri1, string uri2) => $"{uri1.TrimEnd('/')}/{uri2.TrimStart('/')}";


                                                                                Inspired by @Matt Sharpe's answer.






                                                                                share|improve this answer




























                                                                                  0














                                                                                  A simple one liner:



                                                                                  public static string Combine(this string uri1, string uri2) => $"{uri1.TrimEnd('/')}/{uri2.TrimStart('/')}";


                                                                                  Inspired by @Matt Sharpe's answer.






                                                                                  share|improve this answer


























                                                                                    0












                                                                                    0








                                                                                    0







                                                                                    A simple one liner:



                                                                                    public static string Combine(this string uri1, string uri2) => $"{uri1.TrimEnd('/')}/{uri2.TrimStart('/')}";


                                                                                    Inspired by @Matt Sharpe's answer.






                                                                                    share|improve this answer













                                                                                    A simple one liner:



                                                                                    public static string Combine(this string uri1, string uri2) => $"{uri1.TrimEnd('/')}/{uri2.TrimStart('/')}";


                                                                                    Inspired by @Matt Sharpe's answer.







                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Nov 6 '17 at 12:41









                                                                                    Nick N.Nick N.

                                                                                    8,01423161




                                                                                    8,01423161























                                                                                        0














                                                                                        Well, I just concatenate two strings and use regular expressions to do the cleaning part.



                                                                                            public class UriTool
                                                                                        {
                                                                                        public static Uri Join(string path1, string path2)
                                                                                        {
                                                                                        string url = path1 + "/" + path2;
                                                                                        url = Regex.Replace(url, "(?<!http:)/{2,}", "/");

                                                                                        return new Uri(url);
                                                                                        }
                                                                                        }


                                                                                        So, you can use it like this:



                                                                                            string path1 = "http://someaddress.com/something/";
                                                                                        string path2 = "/another/address.html";
                                                                                        Uri joinedUri = UriTool.Join(path1, path2);

                                                                                        // joinedUri.ToString() returns "http://someaddress.com/something/another/address.html"





                                                                                        share|improve this answer






























                                                                                          0














                                                                                          Well, I just concatenate two strings and use regular expressions to do the cleaning part.



                                                                                              public class UriTool
                                                                                          {
                                                                                          public static Uri Join(string path1, string path2)
                                                                                          {
                                                                                          string url = path1 + "/" + path2;
                                                                                          url = Regex.Replace(url, "(?<!http:)/{2,}", "/");

                                                                                          return new Uri(url);
                                                                                          }
                                                                                          }


                                                                                          So, you can use it like this:



                                                                                              string path1 = "http://someaddress.com/something/";
                                                                                          string path2 = "/another/address.html";
                                                                                          Uri joinedUri = UriTool.Join(path1, path2);

                                                                                          // joinedUri.ToString() returns "http://someaddress.com/something/another/address.html"





                                                                                          share|improve this answer




























                                                                                            0












                                                                                            0








                                                                                            0







                                                                                            Well, I just concatenate two strings and use regular expressions to do the cleaning part.



                                                                                                public class UriTool
                                                                                            {
                                                                                            public static Uri Join(string path1, string path2)
                                                                                            {
                                                                                            string url = path1 + "/" + path2;
                                                                                            url = Regex.Replace(url, "(?<!http:)/{2,}", "/");

                                                                                            return new Uri(url);
                                                                                            }
                                                                                            }


                                                                                            So, you can use it like this:



                                                                                                string path1 = "http://someaddress.com/something/";
                                                                                            string path2 = "/another/address.html";
                                                                                            Uri joinedUri = UriTool.Join(path1, path2);

                                                                                            // joinedUri.ToString() returns "http://someaddress.com/something/another/address.html"





                                                                                            share|improve this answer















                                                                                            Well, I just concatenate two strings and use regular expressions to do the cleaning part.



                                                                                                public class UriTool
                                                                                            {
                                                                                            public static Uri Join(string path1, string path2)
                                                                                            {
                                                                                            string url = path1 + "/" + path2;
                                                                                            url = Regex.Replace(url, "(?<!http:)/{2,}", "/");

                                                                                            return new Uri(url);
                                                                                            }
                                                                                            }


                                                                                            So, you can use it like this:



                                                                                                string path1 = "http://someaddress.com/something/";
                                                                                            string path2 = "/another/address.html";
                                                                                            Uri joinedUri = UriTool.Join(path1, path2);

                                                                                            // joinedUri.ToString() returns "http://someaddress.com/something/another/address.html"






                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Oct 18 '18 at 19:50









                                                                                            Peter Mortensen

                                                                                            13.8k1987113




                                                                                            13.8k1987113










                                                                                            answered May 15 '14 at 23:49









                                                                                            Marcio MartinsMarcio Martins

                                                                                            11139




                                                                                            11139























                                                                                                0














                                                                                                I have combined all the previous answers:



                                                                                                    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);
                                                                                                }





                                                                                                share|improve this answer





















                                                                                                • 1





                                                                                                  You could have used VirtualPathUtiliy class to append and remove trailing slashes safely. Check out my answer: stackoverflow.com/a/23399048/3481183

                                                                                                  – Believe2014
                                                                                                  May 1 '14 at 15:38
















                                                                                                0














                                                                                                I have combined all the previous answers:



                                                                                                    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);
                                                                                                }





                                                                                                share|improve this answer





















                                                                                                • 1





                                                                                                  You could have used VirtualPathUtiliy class to append and remove trailing slashes safely. Check out my answer: stackoverflow.com/a/23399048/3481183

                                                                                                  – Believe2014
                                                                                                  May 1 '14 at 15:38














                                                                                                0












                                                                                                0








                                                                                                0







                                                                                                I have combined all the previous answers:



                                                                                                    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);
                                                                                                }





                                                                                                share|improve this answer















                                                                                                I have combined all the previous answers:



                                                                                                    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);
                                                                                                }






                                                                                                share|improve this answer














                                                                                                share|improve this answer



                                                                                                share|improve this answer








                                                                                                edited Oct 18 '18 at 19:56









                                                                                                Peter Mortensen

                                                                                                13.8k1987113




                                                                                                13.8k1987113










                                                                                                answered Apr 25 '13 at 10:51









                                                                                                Per GPer G

                                                                                                322316




                                                                                                322316








                                                                                                • 1





                                                                                                  You could have used VirtualPathUtiliy class to append and remove trailing slashes safely. Check out my answer: stackoverflow.com/a/23399048/3481183

                                                                                                  – Believe2014
                                                                                                  May 1 '14 at 15:38














                                                                                                • 1





                                                                                                  You could have used VirtualPathUtiliy class to append and remove trailing slashes safely. Check out my answer: stackoverflow.com/a/23399048/3481183

                                                                                                  – Believe2014
                                                                                                  May 1 '14 at 15:38








                                                                                                1




                                                                                                1





                                                                                                You could have used VirtualPathUtiliy class to append and remove trailing slashes safely. Check out my answer: stackoverflow.com/a/23399048/3481183

                                                                                                – Believe2014
                                                                                                May 1 '14 at 15:38





                                                                                                You could have used VirtualPathUtiliy class to append and remove trailing slashes safely. Check out my answer: stackoverflow.com/a/23399048/3481183

                                                                                                – Believe2014
                                                                                                May 1 '14 at 15:38











                                                                                                0














                                                                                                Both of these work:



                                                                                                  Uri final = new Uri(Regex.Replace(baseUrl + "/" + relativePath, "(?<!http:)/{2,}", "/"));


                                                                                                Or



                                                                                                  Uri final =new Uri(string.Format("{0}/{1}", baseUrl.ToString().TrimEnd('/'), relativePath.ToString().TrimStart('/')));


                                                                                                I.e. if



                                                                                                baseUrl = "http://tesrurl.test.com/Int18"


                                                                                                and



                                                                                                relativePath = "To_Folder"

                                                                                                output = http://tesrurl.test.com/Int18/To_Folder


                                                                                                Some errors will appear for the code below:



                                                                                                 // If you use the below code, some issues will be there in the final URI
                                                                                                Uri final = new Uri(baseUrl, relativePath);





                                                                                                share|improve this answer






























                                                                                                  0














                                                                                                  Both of these work:



                                                                                                    Uri final = new Uri(Regex.Replace(baseUrl + "/" + relativePath, "(?<!http:)/{2,}", "/"));


                                                                                                  Or



                                                                                                    Uri final =new Uri(string.Format("{0}/{1}", baseUrl.ToString().TrimEnd('/'), relativePath.ToString().TrimStart('/')));


                                                                                                  I.e. if



                                                                                                  baseUrl = "http://tesrurl.test.com/Int18"


                                                                                                  and



                                                                                                  relativePath = "To_Folder"

                                                                                                  output = http://tesrurl.test.com/Int18/To_Folder


                                                                                                  Some errors will appear for the code below:



                                                                                                   // If you use the below code, some issues will be there in the final URI
                                                                                                  Uri final = new Uri(baseUrl, relativePath);





                                                                                                  share|improve this answer




























                                                                                                    0












                                                                                                    0








                                                                                                    0







                                                                                                    Both of these work:



                                                                                                      Uri final = new Uri(Regex.Replace(baseUrl + "/" + relativePath, "(?<!http:)/{2,}", "/"));


                                                                                                    Or



                                                                                                      Uri final =new Uri(string.Format("{0}/{1}", baseUrl.ToString().TrimEnd('/'), relativePath.ToString().TrimStart('/')));


                                                                                                    I.e. if



                                                                                                    baseUrl = "http://tesrurl.test.com/Int18"


                                                                                                    and



                                                                                                    relativePath = "To_Folder"

                                                                                                    output = http://tesrurl.test.com/Int18/To_Folder


                                                                                                    Some errors will appear for the code below:



                                                                                                     // If you use the below code, some issues will be there in the final URI
                                                                                                    Uri final = new Uri(baseUrl, relativePath);





                                                                                                    share|improve this answer















                                                                                                    Both of these work:



                                                                                                      Uri final = new Uri(Regex.Replace(baseUrl + "/" + relativePath, "(?<!http:)/{2,}", "/"));


                                                                                                    Or



                                                                                                      Uri final =new Uri(string.Format("{0}/{1}", baseUrl.ToString().TrimEnd('/'), relativePath.ToString().TrimStart('/')));


                                                                                                    I.e. if



                                                                                                    baseUrl = "http://tesrurl.test.com/Int18"


                                                                                                    and



                                                                                                    relativePath = "To_Folder"

                                                                                                    output = http://tesrurl.test.com/Int18/To_Folder


                                                                                                    Some errors will appear for the code below:



                                                                                                     // If you use the below code, some issues will be there in the final URI
                                                                                                    Uri final = new Uri(baseUrl, relativePath);






                                                                                                    share|improve this answer














                                                                                                    share|improve this answer



                                                                                                    share|improve this answer








                                                                                                    edited Oct 18 '18 at 20:07









                                                                                                    Peter Mortensen

                                                                                                    13.8k1987113




                                                                                                    13.8k1987113










                                                                                                    answered Apr 24 '17 at 7:43









                                                                                                    DAre GDAre G

                                                                                                    1429




                                                                                                    1429























                                                                                                        0














                                                                                                        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!






                                                                                                        share|improve this answer






























                                                                                                          0














                                                                                                          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!






                                                                                                          share|improve this answer




























                                                                                                            0












                                                                                                            0








                                                                                                            0







                                                                                                            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!






                                                                                                            share|improve this answer















                                                                                                            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!







                                                                                                            share|improve this answer














                                                                                                            share|improve this answer



                                                                                                            share|improve this answer








                                                                                                            edited Oct 18 '18 at 20:08









                                                                                                            Peter Mortensen

                                                                                                            13.8k1987113




                                                                                                            13.8k1987113










                                                                                                            answered Mar 22 '18 at 14:19









                                                                                                            pholparpholpar

                                                                                                            1,217917




                                                                                                            1,217917






















                                                                                                                1 2
                                                                                                                next




                                                                                                                protected by Sheridan Oct 22 '14 at 14:51



                                                                                                                Thank you for your interest in this question.
                                                                                                                Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                Would you like to answer one of these unanswered questions instead?



                                                                                                                Popular posts from this blog

                                                                                                                Mossoró

                                                                                                                Error while reading .h5 file using the rhdf5 package in R

                                                                                                                Pushsharp Apns notification error: 'InvalidToken'