Saturday, 8 June 2013

Get Title and Description of URL in Asp.net Like Facebook


Introduction

Here I will explain how to get title & meta description of url in asp.net using C# and VB.NET or get page title and description from page url in asp.net using HTMLAgilityPack in C# and VB.NET.


To get title & description of url we need to write the following code in aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Title and Meta Description from Live URL</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Get Title and Meta Description from Live URL</h3>
<table>
<tr>
<td>
<b>Enter Url:</b>
</td>
<td>
<asp:TextBox ID="txtURL" runat="server" AutoPostBack="True" ontextchanged="txtURL_TextChanged"Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Title:</b>
</td>
<td>
<asp:TextBox ID="txtTiltle" runat="server" Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td valign="top">
<b>Description:</b>
</td>
<td>
<asp:TextBox ID="txtDesc" runat="server" Rows="7" Columns="40" TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Now in code behind add the following namespaces



C# Code

using System;
using System.Net;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

Now add below code in code behind

protected void txtURL_TextChanged(object sender, EventArgs e)
{
String url = txtURL.Text;
//Get Title
WebClient x = new WebClient();
string source = x.DownloadString(url);
txtTiltle.Text = Regex.Match(source, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>",RegexOptions.IgnoreCase).Groups["Title"].Value;
//Method to get Meta Tags
GetMetaTagValues(url);
}
private void GetMetaTagValues(string url)
{
//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 && tag.Attributes["name"].Value =="description")
{
txtDesc.Text = tag.Attributes["content"].Value;
}
}
}
}

No comments:

Post a Comment

Receive All Free Updates Via Facebook.