Remove Non Ascii And Control Characters - CSharp System

CSharp examples for System:String Strip

Description

Remove Non Ascii And Control Characters

Demo Code


using System.Windows.Forms;
using System.IO;//from w ww.  j a  v  a2 s.c o  m
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{
        public static string RemoveNonAsciiAndControlCharacters(string sBody)
        {
            string sReturn = string.Empty;

            StringBuilder oSanitized = new StringBuilder();
            bool bGoodCharacter = true;
            int iVal = 0;

            foreach (char c in sBody)
            {
                bGoodCharacter = true;
                iVal = (int)c;

                // Extended ascii check
                if (iVal > 127 & iVal < 256)
                {
                    bGoodCharacter = false;
                }

                // Non-ASCII and non-Extended ASCII check
                if (iVal > 255)
                {
                    bGoodCharacter = false;
                }

                // Control character check:
                // Control Characters except CR(13) LF (10) and TAB (9)
                if ((iVal >= 0 && iVal <= 31) && (iVal != 10 && iVal != 13 && iVal != 9))
                {
                    bGoodCharacter = false;
                }

                if (bGoodCharacter == true)
                    oSanitized.Append(c);
            }

            sReturn = oSanitized.ToString();

            return sReturn;
        }
}

Related Tutorials