My Favorite String Extension Methods in C#

Since the introduction of Extension Methods in C#, I've found quite a few cool uses for them in my projects. Here are some of my favorite string extension methods.

Download the C# class for the following extension methods:

  • Truncate
    Truncates a string at the given length.
  • ToLineArray
    Splits a string into an array, each element containing one line.
  • ToLineList
    Splits a string into a List<string>, each element containing one line.
  • ReplaceBreaksWithBR
    Replaces line breaks with HTML <br/> elements.
  • DoubleApostrophes
    Doubles (escapes) any apostrophes in the input string. Useful for prepping values to include in a SQL statement.
  • ToHTMLEncoded*
    Encodes the input string using HTML encoding. Useful for escaping dangerous values (script tags, HTML tags) from user input.
  • ToURLEncoded*
    Encodes the input string using URL encoding. Useful for escaping dangerous or URL-breaking values from user input.
  • FromHTMLEncoded*
    Converts from HTML encoded text back to the original HTML.
  • FromURLEncoded*
    Converts from URL encoded text back to the original text.
  • StripHTML
    Removes all HTML tags.

Download C# class!

* Indicates that you must be in the context of an ASP.NET web site to use these methods. This class is from one of my web site projects, so if it's going to be used in another context (Forms app, Console app), you'll need to comment out those methods or it will not compile without referencing System.Web., and even then, they'd be useless because there will never be a Context to access.

Trackback URL: http://www.elijahtaylor.com/trackback/7016b3eb-0a40-496a-be66-0d18f28512f7/My-Favorite-String-Extension-Methods-in-C-.aspx

Comments
Blog post currently doesn't have any comments.
Leave comment



 Security code

details


This web site uses Kentico CMS, the content management system for ASP.NET developers.