开发者

Create http url string

开发者 https://www.devze.com 2023-02-26 21:54 出处:网络
I need a function which will return correct url from url parts (like in browsers) string GetUrl(string actual,string path) {

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?


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


 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.


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.


What about:

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

精彩评论

暂无评论...
验证码 换一张
取 消