tags:

views:

158

answers:

3

How do you extract the Web Site name from a URL or a Link. I have found examples for other languages but not c#. Also the URL / Link will not be the current page that i am on.

e.g. http://www.test.com/SomeOther/Test/Test.php?args=1

From that i need to extract just www.test.com , keep in mind that it wont always be .com and it can be any domain

A: 
this.Request.Url.Host

The other properties in this class will be of interest.

Noon Silk
"Also the URL / Link will not be the current page that i am on."
MPritch
+7  A: 

How about:

new Uri(url).Host

For example:

using System;

class Test
{
    static void Main()
    {
        Uri uri = new Uri("http://www.test.com/SomeOther/Test/Test.php?args=1");
        Console.WriteLine(uri.Host); // Prints www.test.com
    }
}

Check out the docs for the constructor taking a string and the Host property.

Note that if it's not a "trusted" data source (i.e. it could be invalid) you might want to use Uri.TryCreate:

using System;

class Test
{
    static void Main(string[] args)
    {
        Uri uri;
        if (Uri.TryCreate(args[0], UriKind.Absolute, out uri))
        {
            Console.WriteLine("Host: {0}", uri.Host);
        }
        else
        {
            Console.WriteLine("Bad URI!");
        }
    }
}
Jon Skeet
Brilliant exactly what i needed , cant believe i missed that.
RC1140
A: 

Using regex get the content between http:// and first / after that.

Thej
Also if you go the Regex way be sure to exclude sub domains, if you want :)
hab
I guess he wants subdomain, actually even www is a subdomain of test.com
Thej