ekapek
ekapek

Reputation: 219

Create http url string

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?

Upvotes: 0

Views: 13787

Answers (4)

Hallgeir Engen
Hallgeir Engen

Reputation: 971

 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.

Upvotes: 1

Matt
Matt

Reputation: 2851

What about:

string GetUrl(string actual, string path)
{
    return actual.Substring(0, actual.Length - 4).ToString() + "/" + path;
}

Upvotes: 0

Amedio
Amedio

Reputation: 893

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.

Upvotes: 0

Teoman Soygul
Teoman Soygul

Reputation: 25742

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

Upvotes: 3

Related Questions