While working with strings we may have some invalid characters within that string. So below is the code for parsing the string value and getting the filtered and correct string. Here I am checking for the ASCII value of each character present in the string and adding them to the return value if it is the valid one.
Also I am checking for ASCII value to be greater or equal with 32 and less or equal with 177 as the valid range. You can use your own range for validation.
ASCII values:
A-Z (65-90)
a-z (97-122)
0-9 (48-57)
Below method returns the filtered and valid string value.
private string GetValidString(string value) { string retValue = string.Empty; char[] stringArr = value.ToCharArray(); for (int count = 0; count < stringArr.Length; ++count) { if ((int)stringArr[count] >= 32 && (int)stringArr[count] <= 177) { retValue += stringArr[count].ToString(); } else { retValue += " "; } } retValue = retValue.Replace("'", "''"); return retValue; }