[RESOLVED]How to get only the estention of my domain url?

Hi, with this code i can get all my domaine, example :

string DomainName = Request.Url.Host;

i get :

www.mydomain.com

How can i retrive only the estention of my domain? like .COM .IT .FR .CO.UK etc etc ?

            string DomainName = "www.google.com";//Request.Url.Host;
            string ext = DomainName.Substring(DomainName.LastIndexOf("."), DomainName.Length - DomainName.LastIndexOf("."));

it will work with domains having only one extension like you said .com, .in. what about co.uk kind of exts

If you just need to grab the last section of your domain (e.g. .com), you could use the following to retrieve that from your current code which will simply pull the last section of your Host property :

// Get extension
string extension = String.Format(".{0}",Request.Url.Host.Split('.').LastOrDefault());

However, if you need more extensive checking and you know the domain that you are going to be using, you might have to consider stripping off your already known domain name and grabbing whatever remains :

// Get extension
string extension = Request.Url.Host.Replace("www.mydomain.","");

Or you could use a Regular Expression to handle this as well which should cover basically all of the scenarios you might need :

// Get extension using Regular Expression (handles all your scenarios)
var extension = Regex.Replace(Request.Url.Host,@"^(w{3}.)?w+.",""))

You can see an interactive example here or an example of what the expression would match below (all of the colored areas would be replaced) :

Leave a Reply