Get host domain from URL?
Asked Answered
S

12

205

how to get host domain from a string URL?

GetDomain has 1 input "URL", 1 Output "Domain"

Example1

INPUT: http://support.domain.com/default.aspx?id=12345
OUTPUT: support.domain.com

Example2

INPUT: http://www.domain.com/default.aspx?id=12345
OUTPUT: www.domain.com

Example3

INPUT: http://localhost/default.aspx?id=12345
OUTPUT: localhost
Staging answered 8/1, 2013 at 9:36 Comment(1)
It seems the question is for the host in the URL, and not the domain of the host, unless I completely misunderstand "host domain" (as opposed to just "host"). The fact that the answer is along the lines of Uri.Host kind of support that the question should be updated to better reflect and align with the desired examples in the question and the accepted answer.Salify
P
358

You can use Request object or Uri object to get host of url.

Using Request.Url

string host = Request.Url.Host;

Using Uri

Uri myUri = new Uri("http://www.contoso.com:8080/");   
string host = myUri.Host;  // host is "www.contoso.com"
Palmerpalmerston answered 8/1, 2013 at 9:37 Comment(2)
Hi, I wanted to use Request.Url, but Visual Studio still returns Cannot resolve symbol 'Request'. I do not know what is wrong. I use Visual Studio 2010 and Net Framework 4.0. Can anybody explain the symptom? ThanksBoxer
You need to have Request object available which you have in web pages / services but not behind that by default. You can Uri class if you do not have Request object availablePalmerpalmerston
S
95

Try like this;

Uri.GetLeftPart( UriPartial.Authority )

Defines the parts of a URI for the Uri.GetLeftPart method.


http://www.contoso.com/index.htm?date=today --> http://www.contoso.com

http://www.contoso.com/index.htm#main --> http://www.contoso.com

nntp://news.contoso.com/[email protected] --> nntp://news.contoso.com

file://server/filename.ext --> file://server

Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));

Demo

Senn answered 8/1, 2013 at 9:41 Comment(0)
T
30

Use Uri class and use Host property

Uri url = new Uri(@"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);
Trundle answered 8/1, 2013 at 9:39 Comment(0)
E
21

try following statement

 Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
 string pathQuery = myuri.PathAndQuery;
 string hostName = myuri.ToString().Replace(pathQuery , "");

Example1

 Input : http://localhost:4366/Default.aspx?id=notlogin
 Ouput : http://localhost:4366

Example2

 Input : http://support.domain.com/default.aspx?id=12345
 Output: support.domain.com
Epidemic answered 12/7, 2014 at 5:59 Comment(1)
doesn't work if myuri.PathAndQuery is "/" it just replace "/" with ""Overkill
M
13

The best way, and the right way to do it is using Uri.Authority field

Load and use Uri like so :

Uri NewUri;

if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
     Console.Writeline(NewUri.Authority);
}

Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com

Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com

Input : http://localhost/default.aspx?id=12345
Output : localhost

If you want to manipulate Url, using Uri object is the good way to do it. https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx

Mossberg answered 27/3, 2015 at 16:33 Comment(0)
W
3
 var url = Regex.Match(url, @"(http:|https:)\/\/(.*?)\/");

INPUT = "https://stackoverflow.com/questions/";

OUTPUT = "https://stackoverflow.com/";

Whiffletree answered 21/8, 2020 at 19:48 Comment(0)
M
1

Try this

Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));

It will output support.domain.com

Or try

Uri.GetLeftPart( UriPartial.Authority )
Messuage answered 8/1, 2013 at 9:37 Comment(0)
O
1

Here's a solution that will work for all kinds of URLs.

public string GetDomainFromUrl(string url)
{
    url = url.Replace("https://", "").Replace("http://", "").Replace("www.", ""); //Remove the prefix
    string[] fragments = url.Split('/');
    return fragments[0];
}
Ominous answered 26/3, 2022 at 3:5 Comment(0)
M
0

You should construct your string as URI object and Authority property returns what you need.

Methane answered 8/1, 2013 at 9:42 Comment(0)
W
0
    public static string DownloadImage(string URL, string MetaIcon,string folder,string name)
    {
        try
        {
            WebClient oClient = new WebClient();

            string LocalState = Windows.Storage.ApplicationData.Current.LocalFolder.Path;

            string storesIcons = Directory.CreateDirectory(LocalState + folder).ToString();

            string path = Path.Combine(storesIcons, name + ".png");

            
            //si la imagen no es valida ej "/icon.png"
            if (!TextBoxEvent.IsValidURL(MetaIcon))
            {
                Uri uri = new Uri(URL);
                string DownloadImage = "https://" + uri.Host + MetaIcon;

                oClient.DownloadFile(new Uri(DownloadImage), path);
            }
            //si la imagen tiene todo ej https://www.mercadolibre.com/icon.png
            else
            {
                oClient.DownloadFile(new Uri(MetaIcon), path);
            }

            return path;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }
Willodeanwilloughby answered 12/8, 2021 at 0:4 Comment(0)
O
0

it will take only domain name (www.bla.com -> bla)

no Uri required

static string GetDomainNameOnly(string s)
    {
        string domainOnly = "";
        if (!string.IsNullOrEmpty(s))
        {
            if (s.Contains("."))
            {
                string domain = s.Substring(s.LastIndexOf('.', s.LastIndexOf('.') - 1) + 1);
                string countryDomain = s.Substring(s.LastIndexOf('.'));
                domainOnly = domain.Replace(countryDomain, "");
            }
            else
                domainOnly = s;
        }
        return domainOnly;
    }
Obliterate answered 29/4, 2022 at 15:45 Comment(1)
That's not what is asked. The domain should contains www. and .comIlana
W
-4

WWW is an alias, so you don't need it if you want a domain. Here is my litllte function to get the real domain from a string

private string GetDomain(string url)
    {
        string[] split = url.Split('.');
        if (split.Length > 2)
            return split[split.Length - 2] + "." + split[split.Length - 1];
        else
            return url;

    }
Washin answered 27/3, 2015 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.