Mega Code Archive

 
Categories / C# / Data Types
 

Strips all illegal characters from the specified title

using System; using System.IO; using System.Net.Mail; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Configuration; using System.Globalization; using System.Web; using System.Web.Configuration; using System.Threading; using System.Reflection; using System.Collections; using System.Xml; using System.Net; using System.Web.Caching; namespace BlogEngine.Core {   /// <summary>   /// Utilities for the entire solution to use.   /// </summary>   public static class Utils   {     /// <summary>     /// Strips all illegal characters from the specified title.     /// </summary>     public static string RemoveIllegalCharacters(string text)     {       if (string.IsNullOrEmpty(text))         return text;       text = text.Replace(":", string.Empty);       text = text.Replace("/", string.Empty);       text = text.Replace("?", string.Empty);       text = text.Replace("#", string.Empty);       text = text.Replace("[", string.Empty);       text = text.Replace("]", string.Empty);       text = text.Replace("@", string.Empty);       text = text.Replace(".", string.Empty);       text = text.Replace(",", string.Empty);       text = text.Replace("\"", string.Empty);       text = text.Replace("&", string.Empty);       text = text.Replace("'", string.Empty);       text = text.Replace(" ", "-");       text = RemoveDiacritics(text);       text = RemoveExtraHyphen(text);       return HttpUtility.UrlEncode(text).Replace("%", string.Empty);     }     private static string RemoveExtraHyphen(string text)     {       if (text.Contains("--"))       {         text = text.Replace("--", "-");         return RemoveExtraHyphen(text);       }       return text;     }     private static String RemoveDiacritics(string text)     {       String normalized = text.Normalize(NormalizationForm.FormD);       StringBuilder sb = new StringBuilder();       for (int i = 0; i < normalized.Length; i++)       {         Char c = normalized[i];         if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)           sb.Append(c);       }       return sb.ToString();     }   } }