Tuesday, November 8, 2011

Clean invalid characters

Sometimes you need to get rid off some unwanted characters. This function will help you to change them into something else.

public static string cleanInvalidCharacters(string text)
        {
            string newText = text;

            // remove invalid characters
            newText = newText .Replace(@"#", "_");
            newText = newText.Replace(@"%", "_");
            newText = newText.Replace(@"&", "_");
            newText = newText.Replace(@"*", "_");
            newText = newText.Replace(@":", "_");
            newText = newText.Replace(@"<", "_");
            newText = newText.Replace(@">", "_");
            newText = newText.Replace(@"?", "_");
            newText = newText.Replace(@"\", "_");
            newText = newText.Replace(@"/", "_");
            newText = newText.Replace(@"{", "_");
            newText = newText.Replace(@"}", "_");
            newText = newText.Replace(@"|", "_");
            newText = newText.Replace(@"~", "_");
            newText = newText.Replace(@"+", "_");
            newText = newText.Replace(@"-", "_");
            newText = newText.Replace(@",", "_");
            newText = newText.Replace(@"(", "_");
            newText = newText.Replace(@")", "_");
            newText = newText.Replace(@"[", "_");
            newText = newText.Replace(@"]", "_");
            newText = newText.Replace(@"=", "_");
            newText = newText.Replace(@";", "_");
            newText = newText.Replace(@"'", "_");
            newText = newText.Replace(@"@", "_");

            return newText ;
        }

No comments:

Post a Comment