Tuesday, January 22, 2013

How to get Title and Meta Tags with url using asp.net and c#

titleandmetatags
In this article i would like to explain the procedure of getting the Title and Meta Tags with url using asp.net and c# In my previous articles i already explained about Basic comments section using Asp.net and c# , Tracking User information using Asp.net and c# and Currency converter application using Asp.net and c# Here i am going to explain how to fetch the title and meta tags with live url, just like in Facebook.

facebook_login_button


So lets start...
First Open the visual studio asp.net and select one new website
Next,Add 3 Textbox controls to Default.aspx page. 
One Textbox for URL entry 
Second Textbox to display Title from url and 
last Textbox to display Meta Description from url 
Next,Call the following methods in textchanged Event of URL textbox
 

protected void txtFetchURL_TextChanged(object sender, EventArgs e)
    {
        //Get the url
         String url = txtURL.Text;

        //Method to get Title
        GetTitle();

        //Method to get Meta Tags
        GetMetaTags();
    }

Next, write the following code in Title Method
 
private void GetTitle()
{
        //Get Title
        WebClient x = new WebClient();
string source = x.DownloadString(url);

}

Next, write the following code in MetaTags Method
private void GetMetaTags()
{
//Get Meta Tags
        var webGet = new HtmlWeb();
        var document = webGet.Load(url);

        var metaTags = document.DocumentNode.SelectNodes("//meta");

        if (metaTags != null)
        {
            foreach (var tag in metaTags)
            {
                if (tag.Attributes["name"] != null && tag.Attributes["content"] != null)
                {
                    if (tag.Attributes["name"].Value == "description")
                    {

                        txtDescription.Text = tag.Attributes["content"].Value;
                    }
                }
            }
        }
}

In the above method we are getting only description meta tag.
if you want any thing else just add the MetaTag name. 
For Example : tag.Attributes["name"].Value == "keywords"

I hope this article will helps you..if you need any help share your valuable comments..Happy coding

Labels: , , , , , ,