Get host domain from URL?

C#StringUrlHttpwebrequestUri

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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"

Solution 2 - C#

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/1[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

Solution 3 - C#

Use Uri class and use Host property

Uri url = new Uri(@"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);

Solution 4 - C#

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
 

Solution 5 - C#

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

Solution 6 - C#

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

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

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

Solution 7 - C#

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 )

Solution 8 - C#

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

Solution 9 - C#

    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();
        }
    }

Solution 10 - C#

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];
}

Solution 11 - C#

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;
    }

Solution 12 - C#

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;

    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question001View Question on Stackoverflow
Solution 1 - C#AdilView Answer on Stackoverflow
Solution 2 - C#Soner GönülView Answer on Stackoverflow
Solution 3 - C#HabibView Answer on Stackoverflow
Solution 4 - C#SiwachGauravView Answer on Stackoverflow
Solution 5 - C#Guillaume BeauvoisView Answer on Stackoverflow
Solution 6 - C#user7419192View Answer on Stackoverflow
Solution 7 - C#soniccoolView Answer on Stackoverflow
Solution 8 - C#Can Guney AksakalliView Answer on Stackoverflow
Solution 9 - C#Humberto Molina LópezView Answer on Stackoverflow
Solution 10 - C#Cyril GuptaView Answer on Stackoverflow
Solution 11 - C#Vladislav KuznetsovView Answer on Stackoverflow
Solution 12 - C#Xavius PupussView Answer on Stackoverflow