using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System; public class Test { public static void Main() { var originalString = "My name @is ,Wan.;'; Wan"; Console.WriteLine("Original string:"); Console.WriteLine(originalString); Console.WriteLine(); var sanitizedString = RemoveExcept(originalString, alphas: true, spaces: true); Console.WriteLine("Sanitized string:"); Console.WriteLine(sanitizedString); Console.WriteLine(); } /// /// Returns a copy of the original string containing only the set of whitelisted characters. /// /// The string that will be copied and scrubbed. /// If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed. /// If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed. /// If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed. /// If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed. /// If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed. /// If true, all decimal characters (".") will be preserved; otherwise, they will be removed. public static string RemoveExcept(string value, bool alphas = false, bool numerics = false, bool dashes = false, bool underlines = false, bool spaces = false, bool periods = false) { if (string.IsNullOrWhiteSpace(value)) return value; if (new[] { alphas, numerics, dashes, underlines, spaces, periods }.All(x => x == false)) return value; var whitelistChars = new HashSet(string.Concat( alphas ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" : "", numerics ? "01234567890" : "", dashes ? "-" : "", underlines ? "_" : "", periods ? "." : "", spaces ? " " : "" ).ToCharArray()); var scrubbedValue = value.Aggregate(new StringBuilder(), (sb, @char) => { if (whitelistChars.Contains(@char)) sb.Append(@char); return sb; }).ToString(); return scrubbedValue; } }