andrew4582

HtmlEncode src

Sep 24th, 2011
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1.  /// <summary>
  2.         /// HTML-encodes a string and returns the encoded string.
  3.         /// </summary>
  4.         /// <param name="text">The text string to encode. </param>
  5.         /// <returns>The HTML-encoded text.</returns>
  6.         public static string HtmlEncode(string text) {
  7.             if(text == null)
  8.                 return null;
  9.  
  10.             StringBuilder sb = new StringBuilder(text.Length);
  11.  
  12.             int len = text.Length;
  13.             for(int i = 0;i < len;i++) {
  14.                 switch(text[i]) {
  15.  
  16.                     case '<':
  17.                         sb.Append("&lt;");
  18.                         break;
  19.                     case '>':
  20.                         sb.Append("&gt;");
  21.                         break;
  22.                     case '"':
  23.                         sb.Append("&quot;");
  24.                         break;
  25.                     case '&':
  26.                         sb.Append("&amp;");
  27.                         break;
  28.                     default:
  29.                         if(text[i] > 159) {
  30.                             // decimal numeric entity
  31.                             sb.Append("&#");
  32.                             sb.Append(((int)text[i]).ToString(CultureInfo.InvariantCulture));
  33.                             sb.Append(";");
  34.                         }
  35.                         else
  36.                             sb.Append(text[i]);
  37.                         break;
  38.                 }
  39.             }
  40.             return sb.ToString();
  41.         }
Advertisement
Add Comment
Please, Sign In to add comment