0

I need a function which will return correct url from url parts (like in browsers)

string GetUrl(string actual,string path) {
  return newurl;
}

For example:

GetUrl('http://example.com/a/b/c/a.php','z/x/c/i.php') -> http://example.com/a/b/c/z/x/c/i.php

GetUrl('http://example.com/a/b/c/a.php','/z/x/c/i.php') -> http://example.com/z/x/c/i.php

GetUrl('http://example.com/a/b/c/a.php','i.php') -> http://example.com/a/b/c/i.php

GetUrl('http://example.com/a/b/c/a.php','/o/d.php?b=1') -> http//example.com/o/d.php?b=1

GetUrl('http://example.com/a/a.php','./o/d.php?b=1') -> http//example.com/a/o/d.php?b=1

Anu suggestions?

ekapek
  • 209
  • 1
  • 6
  • 20

4 Answers4

3

What you need is the System.UriBuilder class: http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx

There is also a lightweight solution at CodeProject that doesnt depent on System.Web: http://www.codeproject.com/KB/aspnet/UrlBuilder.aspx

There is also one Query String Builder (but I havent tried it before): http://weblogs.asp.net/bradvincent/archive/2008/10/27/helper-class-querystring-builder-chainable.aspx

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • But any light solution without System.Web? – ekapek Apr 16 '11 at 12:09
  • By the way System.Web.UrlBuilder depens on System.Web & displays a GUI. On the other hand, System.UriBuilder does not have a secondary dependency but not as functional as other solutions. – Teoman Soygul Apr 16 '11 at 12:12
1
 public string ConvertLink(string input)
    {
        //Add http:// to link url
        Regex urlRx = new Regex(@"(?<url>(http(s?):[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase);

        MatchCollection matches = urlRx.Matches(input);

        foreach (Match match in matches)
        {
            string url = match.Groups["url"].Value;
            Uri uri = new UriBuilder(url).Uri;
            input = input.Replace(url, uri.AbsoluteUri);
        }
        return input;
    }

The code locate every link inside the string with regex, and then use UriBuilder to add protocol to the link if doesn't exist. Since "http://" is default, it will then be added if no protocol exist.

Hallgeir Engen
  • 841
  • 9
  • 10
0

At this link you can take an example of how to take the domain of the URL, with this, you can add the second part to the string of the url

http://www.jonasjohn.de/snippets/csharp/extract-domain-name-from-url.htm

This is the best way to do it, I think.

See you.

Amedio
  • 895
  • 6
  • 13
0

What about:

string GetUrl(string actual, string path)
{
    return actual.Substring(0, actual.Length - 4).ToString() + "/" + path;
}
Matt
  • 2,691
  • 3
  • 22
  • 36