Generate SEO Friendly URL

Generate SEO Friendly URL from given string in C# for Asp.net Web Application. 

Example 1: Simple Test 

  • Input: CSS is not working in IE? but working in FireFox... asp.net problem
  • Output: css-is-not-working-in-ie-but-working-in-firefox-Asp-Net-problem

Example 2:
 Spaces Testing 
  • Input: asp.net problem url re-writing.... testing the basics
  • Output: Asp-Net-problem-url-re-writing-testing-the-basics

Example 3: Special Character Testing 
  • Input: 23 asp.net problem ### url re-writing.... testing the basics will pay $1000
  • Output: 23-Asp-Net-problem-url-re-writing-testing-the-basics-will-pay-1000


private string GenerateURL(string strTitle) 

//Trim Start and End Spaces. 
strTitle = strTitle.Trim(); 

//Trim "-" Hyphen 
strTitle = strTitle.Trim('-'); 

strTitle = strTitle.ToLower(); 
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray(); 
strTitle = strTitle.Replace("c#", "C-Sharp"); 
strTitle = strTitle.Replace("vb.net", "VB-Net"); 
strTitle = strTitle.Replace("asp.net", "Asp-Net"); 

//Replace . with - hyphen 
strTitle = strTitle.Replace(".", "-"); 

//Replace Special-Characters 
for (int i = 0; i < chars.Length; i++) 

string strChar = chars.GetValue(i).ToString(); 
if (strTitle.Contains(strChar)) 

strTitle = strTitle.Replace(strChar,string.Empty); 



//Replace all spaces with one "-" hyphen 
strTitle = strTitle.Replace(" ", "-"); 

//Replace multiple "-" hyphen with single "-" hyphen. 
strTitle = strTitle.Replace("--", "-"); 
strTitle = strTitle.Replace("---", "-"); 
strTitle = strTitle.Replace("----", "-"); 
strTitle = strTitle.Replace("-----", "-"); 
strTitle = strTitle.Replace("----", "-"); 
strTitle = strTitle.Replace("---", "-"); 
strTitle = strTitle.Replace("--", "-"); 

//Run the code again... 
//Trim Start and End Spaces. 
strTitle = strTitle.Trim(); 

//Trim "-" Hyphen 
strTitle = strTitle.Trim('-'); 

return strTitle; 


Comments