My Favorite String Extension Methods in C#
Saturday, August 29, 2009, 2:55 PM
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:
Truncates a string at the given length.
Splits a string into an array, each element containing one line.
Splits a string into a List<string>, each element containing one line.
Replaces line breaks with HTML <br/> elements.
Doubles (escapes) any apostrophes in the input string. Useful for prepping values to include in a SQL statement.
Encodes the input string using HTML encoding. Useful for escaping dangerous values (script tags, HTML tags) from user input.
Encodes the input string using URL encoding. Useful for escaping dangerous or URL-breaking values from user input.
Converts from HTML encoded text back to the original HTML.
Converts from URL encoded text back to the original text.
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.