Here is the class containing some of the extension methods which I always use in my C#.net 3.5 website projects. The class contains 5 methods as follows.

  1. public static string FromLeft(this string str, int length) Returns the specified number of characters from the start of the string.
  2. public static string FromRight(this string str, int length) Returns the specified number of characters from the end.
  3. public static string MakeSEOFriendly(this string str) Makes the string seo friendly by only allowing following characters [a-z0-9,-_].
  4. public static string HtmlEncode(this string str) Returns the html encoded version of the string (just a wrapper).
  5. public static string HtmlDecode(this string str) Returns the html decoded version of the string (just a wrapper).

All methods will return an empty string ("") if the string on which it gets called is an empty string or is a null string (String.IsNullOrEmpty()).

Code follows

using System; public static class MyExtensions{ public static string FromLeft(this string str, int length){ if (string.IsNullOrEmpty(str)) return ""; if(str.Length < length) return str;return str.Substring(0, length);}public static string FromRight(this string str, int length){if (string.IsNullOrEmpty(str)) return ""; if(str.Length < length) return str;return str.Substring(str.Length - length, length);} public static string HtmlEncode(this string str){ if (string.IsNullOrEmpty(str)) return ""; return System.Web.HttpUtility.HtmlEncode(str);} public static string HtmlDecode(this string str){if (string.IsNullOrEmpty(str)) return ""; return System.Web.HttpUtility.HtmlDecode(str);} public static string MakeSEOFriendly(this string str){if (string.IsNullOrEmpty(str)) return ""; System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex( @"[^a-z0-9,\-_]+", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled );return reg.Replace(str, "-").Trim("-".ToCharArray());}

Using the code

Simply put this code inside the app_code folder. For example create a file "extensions.cs" and paste the code in to it. Now all the string objects will have all the 5 methods as their members.

Example usage

string SEOTitle = txtTitle.Text.MakeSEOFriendly();//The SEOTitle variable now has the seo friendly version of the title.

Happy coding!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList