201

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
John Saunders
  • 160,644
  • 26
  • 247
  • 397
001
  • 62,807
  • 94
  • 230
  • 350
  • 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. – NoOneSpecial Mar 13 '19 at 14:54

12 Answers12

347

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"
Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Adil
  • 146,340
  • 25
  • 209
  • 204
  • 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? Thanks – Michal Jan 26 '16 at 12:21
  • 1
    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 available – Adil Jan 26 '16 at 12:27
93

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/123456@contoso.com --> 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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
30

Use Uri class and use Host property

Uri url = new Uri(@"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);
Habib
  • 219,104
  • 29
  • 407
  • 436
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
SiwachGaurav
  • 1,918
  • 2
  • 17
  • 16
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

3
 var url = Regex.Match(url, @"(http:|https:)\/\/(.*?)\/");

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

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

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 )
soniccool
  • 5,790
  • 22
  • 60
  • 98
0

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

Can Guney Aksakalli
  • 1,320
  • 1
  • 11
  • 24
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();
        }
    }
Humberto
  • 428
  • 5
  • 7
0

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];
}
Cyril Gupta
  • 13,505
  • 11
  • 64
  • 87
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;
    }
-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;

    }
Xavius Pupuss
  • 160
  • 1
  • 6