Getting a domain name from URl

I need to extract the exact domain name from any Url.

For example,

This is what I have tried so far, this does not return the exact results I expect, can someone help me here.

   public static string GetDomainName(string domainURL) {
            string domain = new Uri(domainURL).DnsSafeHost.ToLower();
            var tokens = domain.Split('.');
            if (tokens.Length > 2)
            {
                //Add only second level exceptions to the < 3 rule here
                string[] exceptions = { "info", "firm", "name", "com", "biz", "gen", "ltd", "web", "net", "pro", "org" };
                var validTokens = 2 + ((tokens[tokens.Length - 2].Length < 3 || exceptions.Contains(tokens[tokens.Length - 2])) ? 1 : 0);
                domain = string.Join(".", tokens, tokens.Length - validTokens, validTokens);
            }
            return domain;
    }

      

+3


source to share


4 answers


Use the URI class found in the System namespace

Uri myUri = new Uri("http://www.something.com/");

      



It has properties like host which should make you want what you need ...

+3


source


Please try this code:

public string GetDomainName(string domainURL)
{
    string domain = new Uri(domainURL).DnsSafeHost.ToLower();
    domain = domainURL.Split(':')[0] + "://" + domain;
    return domain;
}

      

I think you need to split and get the protocol from the beginning of the line and add it to the domain. If you pass any URL without a type protocol http://

, the method new Uri()

will throw an error.



So, I think the code domainURL.Split(':')[0] + "://" + domain;

will work for you.

Consult the suggested input.

+1


source


Here is the code to extract the parts using the Uri class and then put the parts you want to merge together.

However, it seemed to you that you specifically wanted to delete the " www. " Fragment , so I used a string replacement for that.

Uri MyUri = new Uri(domainURL);

string Result = MyUri.GetLeftPart(UriPartial.Scheme);

Result += MyUri.GetComponents(UriComponents.Host, UriFormat.SafeUnescaped).Replace("www.", string.Empty);

return Result;

      

0


source


try this:

        Uri myUri = new Uri("http://www.something.subdomain.com");
        string host = myUri.Host;

      

host is what you are looking for.

0


source







All Articles